-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
257 lines (237 loc) · 7.7 KB
/
server.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
// Handle VPN server (azure client) connections
package main
import (
"bytes"
"crypto/rand"
"crypto/tls"
"errors"
"io"
"net"
"strings"
"time"
)
type serverOperation string
const (
serverRelay serverOperation = "relay"
serverTimeout = 30 * time.Second
)
type serverCommand struct {
op serverOperation
num uint64
hostname string
sessionID []byte
clientIP net.IP
clientPort int
}
// Handle new server connection
func handleServer(num uint64, conn *tls.Conn, suffix *suffix) {
lg.PrintSessionf("New server connection from %s", num, ' ', 0, conn.RemoteAddr())
conn.SetDeadline(time.Now().Add(serverTimeout))
b := make([]byte, 24)
n, err := io.ReadAtLeast(conn, b, 4)
if err != nil {
lg.PrintSessionf("Invalid server connection", num, ' ', 0)
return
}
if bytes.Equal(b[:4], []byte("ACTL")) {
lg.PrintSessionf("Starting server control session from %s for suffix %s", num, 'L', 1, conn.RemoteAddr(), suffix.suffix)
handleServerControl(num, conn, suffix.suffix)
return
}
if n < 24 {
if _, err := io.ReadFull(conn, b[n:]); err != nil {
lg.PrintSessionf("Invalid server connection", num, ' ', 0)
return
}
}
if bytes.Equal(b, []byte("AZURE_CONNECT_SIGNATURE!")) {
lg.PrintSessionf("Starting server data session from %s for suffix %s", num, 'S', 1, conn.RemoteAddr(), suffix.suffix)
handleServerData(num, conn)
return
}
lg.PrintSessionf("Invalid server connection", num, ' ', 0)
}
// Handle azure control session.
// conn automatically closes on return, do not fork.
func handleServerControl(num uint64, conn *tls.Conn, suffix string) {
random := make([]byte, 20)
if _, err := rand.Read(random); err != nil {
lg.PrintSessionf("Failed to generate a random", num, 'L', 3)
return
}
// Send control pack to client
p := pack{elements: map[string]packElement{
"ControlKeepAlive": newPackElementInt(40000),
"ControlTimeout": newPackElementInt(60000),
"DataTimeout": newPackElementInt(40000),
"SslTimeout": newPackElementInt(5000),
"Random": newPackElementData(random),
}}
if _, err := p.send(conn, true); err != nil {
lg.PrintSessionf("Session aborted: %s", num, 'L', 3, err)
return
}
// Receive pack from client
p, err := recvPack(conn, true)
if err != nil {
lg.PrintSessionf("Session aborted: %s", num, 'L', 3, err)
return
}
// Authenticate
var hostname string
state := conn.ConnectionState()
if len(state.PeerCertificates) == 0 {
var ok bool
hostname, ok = p.getString("CurrentHostName", true)
if !ok {
lg.PrintSessionf("Session aborted: no hostname provided by peer", num, 'L', 3)
return
}
clientInfo, ok := auths.find(hostname, suffix)
if !ok {
lg.PrintSessionf("Session aborted: hostname %s is invalid", num, 'L', 3, hostname)
return
}
switch clientInfo.method {
case authNone:
lg.PrintSessionf("Authentication completed anonymously", num, 'L', 2)
case authPassword:
if hash, ok := p.getData("PasswordHash"); ok && clientInfo.checkPassword(hostname, random, hash) {
lg.PrintSessionf("Authentication completed with password", num, 'L', 2)
} else {
lg.PrintSessionf("Session aborted: incorrect password", num, 'L', 3)
return
}
case authCert:
// Peer should but didn't provide certificate during TLS handshake
lg.PrintSessionf("Session aborted: authentication failed with certificate", num, 'L', 3)
return
default:
lg.PrintSessionf("Session aborted: unsupported authentication method", num, 'L', 3)
return
}
} else {
// Already authenticated by TLS
hostname = strings.ToLower(state.PeerCertificates[0].Subject.CommonName)
lg.PrintSessionf("Authentication completed with certificate", num, 'L', 2)
}
// Add session
if _, err := conn.Write([]byte{1}); err != nil {
lg.PrintSessionf("Session aborted: %s", num, 'L', 3, err)
return
}
if err := serverKeepAlive(conn); err != nil {
lg.PrintSessionf("Session aborted: %s", num, 'L', 3, err)
return
}
// unbuffered is ok but may block as sending signal to server takes time
ch := make(chan serverCommand, 50)
// channel operations other than receiving must be done in sessions to avoid race
sessions.addServer(num, hostname, suffix, conn, ch)
lg.PrintSessionf("%s is online", num, 'L', 2, hostname)
// Session starts
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case c, ok := <-ch:
if !ok {
lg.PrintSessionf("Session closed", num, 'L', 3)
return
}
switch c.op {
case serverRelay:
// send signal to server
conn.SetDeadline(time.Now().Add(serverTimeout))
// In this implemention, relay server is the control server though they can differ
// Get fresh suffix because it may get changed during a control session
if sfx := suffixes.get(suffix); sfx != nil {
remoteAddr := conn.RemoteAddr().(*net.TCPAddr)
localAddr := conn.LocalAddr().(*net.TCPAddr)
p := pack{elements: map[string]packElement{
"opcode": newPackElementString(string(c.op)),
"hostname": newPackElementString(c.hostname),
"session_id": newPackElementData(c.sessionID),
"client_port": newPackElementInt(uint32(c.clientPort)),
"server_port": newPackElementInt(uint32(remoteAddr.Port)),
"relay_address": newPackElementString(sfx.control),
"relay_port": newPackElementInt(uint32(localAddr.Port)),
"cert_hash": newPackElementData(sfx.certHash[:]),
}}
p.addIP("client_ip", c.clientIP)
p.addIP("server_ip", remoteAddr.IP)
_, err := conn.Write([]byte{1})
if err == nil {
_, err = p.send(conn, true)
}
if err == nil {
lg.PrintSessionf("Signal sent to the server for client session %d", num, 'L', 2, c.num)
b := make([]byte, 1)
_, err = conn.Read(b)
} else {
lg.PrintSessionf("Failed to send signal to server: %s", num, 'L', 2, err)
}
if err != nil {
sessions.delServer(num, hostname)
}
} else {
lg.PrintSessionf("Suffix %s is no longer valid", num, 'L', 3, suffix)
sessions.delServer(num, hostname)
}
}
case <-ticker.C:
conn.SetDeadline(time.Now().Add(serverTimeout))
if err := serverKeepAlive(conn); err != nil {
// if channel is unbuffered, launch as goroutine to avoid deadlock with sending
sessions.delServer(num, hostname)
}
}
}
}
func serverKeepAlive(conn *tls.Conn) error {
if _, err := conn.Write([]byte{0}); err != nil {
return err
}
b := make([]byte, 1)
if _, err := conn.Read(b); err != nil {
return err
}
if b[0] != 0 {
return errors.New("invalid response from server")
}
return nil
}
// Handle azure data session.
// conn automatically closes on return, do not fork.
func handleServerData(num uint64, conn *tls.Conn) {
// Receive pack from client
p, err := recvPack(conn, true)
if err != nil {
lg.PrintSessionf("Session aborted: %s", num, 'S', 3, err)
return
}
hostname, ok := p.getString("hostname", false)
if !ok {
lg.PrintSessionf("Session aborted: no hostname provided by peer", num, 'S', 3)
return
}
sessionID, ok := p.getData("session_id")
if !ok || len(sessionID) != 20 {
lg.PrintSessionf("Session aborted: failed to get session ID from server", num, 'S', 3)
return
}
// Get client connection
if cnum, c := sessions.serverRespond(num, conn, hostname, sessionID); c != nil {
defer sessions.delRelay(cnum)
if _, err := conn.Write([]byte{1}); err != nil {
lg.PrintSessionf("Session aborted: %s", num, 'S', 3, err)
return
}
lg.PrintSessionf("Relaying data from client session %d", num, 'S', 2, cnum)
conn.SetDeadline(time.Time{})
n, _ := io.Copy(conn, c)
lg.PrintSessionf("Server session closed: relayed %d bytes from client to server", num, 'S', 3, n)
} else {
lg.PrintSessionf("Session aborted: can't find the client session", num, 'S', 3)
}
}