-
Notifications
You must be signed in to change notification settings - Fork 5
/
vpnazure.go
110 lines (95 loc) · 2.43 KB
/
vpnazure.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
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"os"
"time"
"vpnazure-go/internal/logger"
)
var listenAddr = flag.String("b", "", "Listening address and port")
var suffixFile = flag.String("suffix", "", "File that contains DNS suffixes of the service")
var authFile = flag.String("auth", "", "File that contains server credentials")
var logFile = flag.String("log", "", "Path to the log file")
var version = "unknown"
var build = "unknown"
// Global variables are thread-safe
var (
lg logger.Logger
suffixes suffixList
auths authList
sessions sessionList
)
func main() {
flag.Parse()
if flag.NArg() > 0 || len(os.Args) == 1 {
fmt.Fprintf(os.Stderr, "vpnazure-go version %s (build %s) usage:\n", version, build)
flag.PrintDefaults()
os.Exit(1)
}
// Open log file or write to stdout
lg.Open(*logFile, true)
defer lg.Close()
// Read DNS suffix from file
if n := suffixes.read(*suffixFile); n > 0 {
lg.Printf("Loaded %d suffixes", n)
} else {
log.Fatalf("At least 1 DNS suffix is needed")
}
// Read server credentials
if n := auths.read(*authFile); n > 0 {
lg.Printf("Loaded %d server credentials", n)
} else {
log.Fatalf("At least 1 server credential is needed")
}
go listenSignal()
// Start listener
config := &tls.Config{GetConfigForClient: getConfigForClient}
listener, err := tls.Listen("tcp", *listenAddr, config)
if err != nil {
log.Fatalln(err)
}
// Print session status with ticker
go func() {
ticker := time.Tick(15 * time.Minute)
for range ticker {
sessions.printStatus()
}
}()
sessions.servers = make(map[string]serverSession)
sessions.relaying = make(map[uint64]relayingSession)
sessions.pending = make(map[uint64]pendingSession)
// connection counter
var num uint64
for {
conn, err := listener.Accept()
if err != nil {
lg.Println(err)
continue
}
if tlsConn, ok := conn.(*tls.Conn); ok {
num++
go func(num uint64) {
defer conn.Close()
if err := tlsConn.Handshake(); err != nil {
lg.PrintSessionf("TLS handshake failed: %s", num, ' ', 0, err)
return
}
state := tlsConn.ConnectionState()
hostname, suffix, server, ok := suffixes.parse(state.ServerName)
if !ok {
lg.PrintSessionf("SNI %s does not match any suffix", num, ' ', 0, state.ServerName)
return
}
if server {
handleServer(num, tlsConn, suffix)
} else {
handleClient(num, tlsConn, hostname)
}
}(num)
} else {
conn.Close()
}
}
}