-
Notifications
You must be signed in to change notification settings - Fork 1
/
tunnel.go
234 lines (209 loc) · 6.62 KB
/
tunnel.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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"os/exec"
"net"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/vishvananda/netlink"
)
const wgIfName = "wg-tunnel"
const listenPort = 51820
const wgAddrServer = "10.0.0.1/24"
const wgAddrClient = "10.0.0.2/24"
const nginxPublishedPort = "8080"
const nginxBindAddr = "10.0.0.1"
const peerAddrServer = "10.0.0.1/32"
const peerAddrClient = "10.0.0.2/32"
func main() {
fmt.Println ("<Wireguard Tunnel>")
if len(os.Args) == 1 {
/* Deploy a server endpoint */
fmt.Println ("Deploying server side of the tunnel")
serverEndpoint()
} else {
/* Deploy a client endpoint */
fmt.Println ("Deploying client side of the tunnel")
serverPublicKey, err := wgtypes.ParseKey(os.Args[1])
if err != nil {
fmt.Println ("Invalid arguments, exiting")
os.Exit(1)
}
clientPrivateKey, err := wgtypes.ParseKey(os.Args[2])
if err != nil {
fmt.Println ("Invalid arguments, exiting")
os.Exit(1)
}
serverPublicIP := os.Args[3]
clientEndpoint(serverPublicKey, clientPrivateKey, serverPublicIP)
}
}
func serverEndpoint() {
configureWgInterfaceNetlink(wgAddrServer)
configureWgInterfaceProtocolServer()
runDockerNginx()
}
func clientEndpoint(serverPublicKey wgtypes.Key, clientPrivateKey wgtypes.Key, serverPublicIP string) {
configureWgInterfaceNetlink(wgAddrClient)
configureWgInterfaceProtocolClient(serverPublicKey, clientPrivateKey, serverPublicIP)
runDockerCurl()
}
func configureWgInterfaceNetlink(wgAddr string) {
wgIf, err := netlink.LinkByName(wgIfName)
if err == nil {
/* Remove existing interface */
fmt.Printf ("Interface exists: %s, deleting to recreate\n", wgIfName)
netlink.LinkDel(wgIf)
}
addIf := exec.Command("ip", "link", "add", wgIfName, "type", "wireguard")
if err := addIf.Run(); err != nil {
fmt.Printf ("Error adding wireguard interface [ip link add ...]: %v\n", err)
os.Exit(1)
} else {
fmt.Println ("Interface added")
}
wgIf, _ = netlink.LinkByName(wgIfName)
addr, _ := netlink.ParseAddr(wgAddr)
netlink.AddrAdd(wgIf, addr)
netlink.LinkSetUp(wgIf)
}
func configureWgInterfaceProtocolClient(serverPublicKey wgtypes.Key, clientPrivateKey wgtypes.Key, serverPublicIP string) {
c, err := wgctrl.New()
if err != nil {
fmt.Printf ("Error creating wgctrl instance: %v\n", err)
os.Exit(1)
}
_, ipnet, err := net.ParseCIDR(peerAddrServer)
if err != nil {
fmt.Println ("Can't parse server endpoint's tunnel ip address")
os.Exit(1)
}
serverPubUDP, err := net.ResolveUDPAddr("", serverPublicIP + ":" + fmt.Sprintf("%d", listenPort))
if err != nil {
fmt.Printf ("Can't parse server endpoint's public ip address: %v\n", err)
os.Exit(1)
}
peerConfig := wgtypes.PeerConfig {
PublicKey : wgtypes.Key(serverPublicKey),
ReplaceAllowedIPs : true,
AllowedIPs : []net.IPNet{ *ipnet },
Endpoint : serverPubUDP,
}
clientConfig := wgtypes.Config {
PrivateKey : &clientPrivateKey,
ReplacePeers : true,
Peers : []wgtypes.PeerConfig{peerConfig},
}
if err := c.ConfigureDevice(wgIfName, clientConfig); err != nil {
fmt.Printf ("Error applying client configuariont: %v\n", err)
os.Exit(1)
} else {
fmt.Println ("Successfully applied client endpoint configuration")
}
}
func configureWgInterfaceProtocolServer() {
c, err := wgctrl.New()
if err != nil {
fmt.Printf ("Error creating wgctrl instance: %v\n", err)
os.Exit(1)
}
peerPrivateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
fmt.Printf ("Error generating key pair for peer: %v\n", err)
os.Exit(1)
}
peerPublicKey := peerPrivateKey.PublicKey()
_, ipnet, err := net.ParseCIDR(peerAddrClient)
if err != nil {
fmt.Printf ("Can't parse client's tunnel ip address: %v\n", err)
os.Exit(1)
}
peerConfig := wgtypes.PeerConfig {
PublicKey : peerPublicKey,
ReplaceAllowedIPs : true,
AllowedIPs : []net.IPNet{ *ipnet },
}
serverPrivateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
fmt.Printf ("Error generating server key pair: %v\n", err)
os.Exit(1)
}
serverPublicKey := serverPrivateKey.PublicKey()
listenPortCopy := listenPort
serverConfig := wgtypes.Config {
PrivateKey : &serverPrivateKey,
ListenPort : &listenPortCopy,
ReplacePeers : true,
Peers : []wgtypes.PeerConfig{peerConfig},
}
if err := c.ConfigureDevice(wgIfName, serverConfig); err != nil {
fmt.Printf ("Error applying server configuariont: %v\n", err)
os.Exit(1)
} else {
fmt.Println ("Successfully applied server endpoint configuration")
}
fmt.Println("On client, run specifying ip of server where deployment was made:")
fmt.Printf("\t$ ./tunnel %s %s <public ip of server>\n", serverPublicKey.String(), peerPrivateKey.String())
c.Close()
}
func runDockerNginx() {
nginxCommand := exec.Command("docker", "run", "--rm", "-d", "-p",
fmt.Sprintf("%s:80", nginxPublishedPort), "--name", "nginx", "nginx")
fmt.Println ("Starting Nginx container")
if out, err := nginxCommand.CombinedOutput(); err != nil {
fmt.Println (string(out))
os.Exit(1)
} else {
fmt.Printf ("Nginx started on %s:%s, to test run on the client:\n", nginxBindAddr, nginxPublishedPort)
fmt.Println ("\t$ curl" + " " + nginxBindAddr + ":" + nginxPublishedPort)
fmt.Println ("Issue ^-C to tear down the setup")
waitForInterrupt(stopDockerNginx)
}
}
func stopDockerNginx() {
nginxCommand := exec.Command("docker", "container", "stop", "nginx")
if out, err := nginxCommand.CombinedOutput(); err != nil {
fmt.Println (string(out))
os.Exit(1)
} else {
fmt.Println ("Nginx stopped, exiting gracefully")
}
}
func runDockerCurl() {
clientCommand := exec.Command("docker", "run", "--rm", "-d", "-it", "--name", "curlContainer", "tutum/curl")
fmt.Println ("Starting curl container")
if out, err := clientCommand.CombinedOutput(); err != nil {
fmt.Println (string(out))
os.Exit(1)
} else {
fmt.Printf ("Client curl image started successfully, to test, run on other terminal:\n")
fmt.Printf("\t$ docker exec -it curlContainer curl %s:%s\n", nginxBindAddr, nginxPublishedPort)
fmt.Println ("Issue ^-C to tear down the setup")
waitForInterrupt(stopDockerCurl)
}
}
func stopDockerCurl() {
nginxCommand := exec.Command("docker", "container", "stop", "curlContainer")
if out, err := nginxCommand.CombinedOutput(); err != nil {
fmt.Println (string(out))
os.Exit(1)
} else {
fmt.Println ("Client ubuntu image stopped, exiting gracefully")
}
}
func waitForInterrupt(f func ()) {
var end_waiter sync.WaitGroup
end_waiter.Add(1)
var signal_channel chan os.Signal
signal_channel = make(chan os.Signal, 1)
signal.Notify(signal_channel, os.Interrupt)
go func() {
<-signal_channel
f()
end_waiter.Done()
}()
end_waiter.Wait()
}