-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
217 lines (187 loc) · 5.35 KB
/
util.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
package main
import (
"compress/gzip"
"encoding/json"
"errors"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"strings"
"text/template"
"github.com/aos/wgdash/wgcli"
"github.com/apparentlymart/go-cidr/cidr"
)
var fileName = "server_config.json"
// LoadServerConfig looks for the server config and if it can't find it,
// will make a new one and return the struct
func LoadServerConfig() *WgServer {
f, err := ioutil.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return CreateServerConfig()
}
log.Fatalf("Unable to open server config file: %s", err)
}
var wgServer WgServer
err = json.Unmarshal(f, &wgServer)
if err != nil {
log.Fatalf("Incorrectly formatted JSON server config: %s", err)
}
// TODO: this could potentially break if we find a template that does
// not have port, or other values filled out. Need to initialize with
// defaults
if wgServer.PublicKey == "" || wgServer.PrivateKey == "" {
keys, err := wgcli.GenerateKeyPair()
if err != nil {
log.Fatalf("unable to generate wg key pair: %s", err)
}
wgServer.PublicKey = keys["publicKey"]
wgServer.PrivateKey = keys["privateKey"]
err = wgServer.saveBothConfigs()
if err != nil {
log.Fatalf("unable to save server configs: %s", err)
}
}
if _, err := os.Stat(wgServer.WgConfigPath); os.IsNotExist(err) {
wgServer.saveBothConfigs()
if err != nil {
log.Fatalf("unable to save server configs: %s", err)
}
}
return &wgServer
}
// CreateServerConfig creates a new server config file and returns the struct
func CreateServerConfig() *WgServer {
keys, err := wgcli.GenerateKeyPair()
if err != nil {
log.Fatalf("unable to generate wg key pair: %s", err)
}
// TODO: read from a template
wgServer := &WgServer{
Port: "58210",
VirtualIP: "10.22.0.1",
CIDR: "16",
DNS: "1.1.1.1",
WgConfigPath: "/etc/wireguard/wg0.conf",
PublicKey: keys["publicKey"],
PrivateKey: keys["privateKey"],
Peers: []Peer{},
}
err = wgServer.getPublicIPAddr()
if err != nil {
log.Fatalf("unable to get public IP address: %s", err)
}
err = wgServer.saveBothConfigs()
if err != nil {
log.Fatalf("unable to save server and wg configs: %s", err)
}
return wgServer
}
func (s *WgServer) saveBothConfigs() error {
j, err := json.MarshalIndent(s, "", " ")
if err != nil {
log.Printf("unable to save server config: %s", err)
return err
}
err = ioutil.WriteFile(fileName, j, 0600)
if err != nil {
log.Printf("unable to write server config JSON file: %s", err)
return err
}
tmpl := template.Must(template.ParseFiles("templates/server.conf.tmpl"))
f, err := os.OpenFile(s.WgConfigPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Printf("unable to open wireguard config file: %s", err)
return err
}
defer f.Close()
err = tmpl.Execute(f, s)
if err != nil {
log.Printf("error writing template to file: %s", err)
return err
}
return nil
}
func (s *WgServer) getPublicIPAddr() error {
// Alternative: ip -4 a show wlp2s0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
// Note: this does not make an actual connection and can be used offline
conn, err := net.Dial("udp", "1.1.1.1:80")
if err != nil {
return err
}
defer conn.Close()
s.PublicIP = conn.LocalAddr().(*net.UDPAddr).IP.String()
return nil
}
func (s *WgServer) nextAvailableIP(assignedIP string) (string, error) {
usedIPs := make(map[string]struct{})
usedIPs[s.VirtualIP] = struct{}{}
for _, p := range s.Peers {
usedIPs[p.VirtualIP] = struct{}{}
}
_, ipNet, err := net.ParseCIDR(s.VirtualIP + "/" + s.CIDR)
if err != nil {
return "", errors.New("nextAvailableIP: server IP address incorrect")
}
if assignedIP != "" {
ip, _, err := net.ParseCIDR(assignedIP + "/" + s.CIDR)
if err != nil {
return "", errors.New("addPeer: incorrectly formatted IP address")
}
if !ipNet.Contains(ip) {
return "", errors.New("addPeer: assigned peer IP not in server subnet")
}
if _, ok := usedIPs[assignedIP]; !ok {
return assignedIP, nil
}
}
networkIP, broadcastIP := cidr.AddressRange(ipNet)
// Don't use network address and broadcast address
firstIP := cidr.Inc(networkIP)
lastIP := cidr.Dec(broadcastIP)
for i := firstIP; !lastIP.Equal(i); i = cidr.Inc(i) {
if _, ok := usedIPs[i.To4().String()]; !ok {
return i.To4().String(), nil
}
}
return "", errors.New("nextAvailableIP: no available IPs")
}
// CheckServerActive queries systemd to check that wg server is up
func (s *WgServer) CheckServerActive() {
cmd := exec.Command("systemctl", "is-active", "--quiet", "wg-quick@wg0")
if err := cmd.Run(); err != nil {
s.Active = false
}
s.Active = true
}
// ActivateServer starts wg server through systemd wg-quick unit
func (s *WgServer) ActivateServer() {
cmd := exec.Command("systemctl", "start", "wg-quick@wg0")
if err := cmd.Run(); err != nil {
s.Active = false
}
s.Active = true
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func gzipHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
h.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
})
}