-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
323 lines (271 loc) · 9.85 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
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
314
315
316
317
318
319
320
321
322
323
package wgrpcd
import (
"context"
"os"
"github.com/joncooperworks/grpcauth"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
)
const (
maxPort = 65535
)
// Server implements the operations exposed in the profobuf definitions for the gRPC server.
type Server struct {
UnimplementedWireguardRPCServer
logger Logger
}
// CreatePeer adds a new Wireguard peer to the VPN.
func (s *Server) CreatePeer(ctx context.Context, request *CreatePeerRequest) (*CreatePeerResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
wireguard, err := New(request.GetDeviceName())
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist: %s", request.GetDeviceName())
}
return nil, status.Errorf(codes.Internal, "error creating peer: %v", err)
}
allowedIPs, err := StringsToIPNet(request.GetAllowedIPs())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "an ip address in AllowedIPs is invalid, error: %v", err)
}
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
return nil, status.Errorf(codes.Internal, "error generating private key")
}
publicKey := key.PublicKey()
peerConfig, err := wireguard.AddNewPeer(allowedIPs, publicKey)
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error adding peer to wireguard interface: %v", err)
}
s.logger.Printf("Client '%s' added peer '%s'", auth.ClientIdentifier, publicKey.String())
response := &CreatePeerResponse{
PublicKey: peerConfig.PublicKey.String(),
PrivateKey: key.String(),
AllowedIPs: IPNetsToStrings(allowedIPs),
ServerPublicKey: wireguard.ServerPublicKey.String(),
}
return response, nil
}
// RekeyPeer revokes a client's old public key and replaces it with a new one.
func (s *Server) RekeyPeer(ctx context.Context, request *RekeyPeerRequest) (*RekeyPeerResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
wireguard, err := New(request.GetDeviceName())
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error rekeying peer: %v", err)
}
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
return nil, status.Errorf(codes.Internal, "error generating private key")
}
allowedIPs, err := StringsToIPNet(request.GetAllowedIPs())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "an ip address in AllowedIPs is invalid, error: %v", err)
}
publicKey, err := wgtypes.ParseKey(request.GetPublicKey())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid public key: %v", err)
}
s.logger.Printf("Client '%s' attempting to rekey peer '%s'", auth.ClientIdentifier, publicKey.String())
peerConfig, err := wireguard.RekeyClient(allowedIPs, publicKey, key.PublicKey())
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error rekeying peer: %v", err)
}
s.logger.Printf("Client '%s' rekeyed peer '%s'", auth.ClientIdentifier, publicKey.String())
response := &RekeyPeerResponse{
PublicKey: peerConfig.PublicKey.String(),
PrivateKey: key.String(),
AllowedIPs: IPNetsToStrings(allowedIPs),
ServerPublicKey: wireguard.ServerPublicKey.String(),
}
return response, nil
}
// RemovePeer deletes a peer from the Wireguard interface.
func (s *Server) RemovePeer(ctx context.Context, request *RemovePeerRequest) (*RemovePeerResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
wireguard := &Wireguard{
DeviceName: request.GetDeviceName(),
}
publicKey, err := wgtypes.ParseKey(request.GetPublicKey())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid public key: %v", err)
}
s.logger.Printf("Client '%s' attempting to remove peer '%s'", auth.ClientIdentifier, publicKey.String())
err = wireguard.RemovePeer(publicKey)
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error removing peer: %v", err)
}
s.logger.Printf("Client '%s' removed peer '%s'", auth.ClientIdentifier, publicKey.String())
response := &RemovePeerResponse{
Removed: true,
}
return response, nil
}
// ListPeers returns all peers from a Wireguard device.
func (s *Server) ListPeers(ctx context.Context, request *ListPeersRequest) (*ListPeersResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
s.logger.Printf("Client '%s' listing peers", auth.ClientIdentifier)
wireguard := &Wireguard{
DeviceName: request.GetDeviceName(),
}
devicePeers, err := wireguard.Peers()
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error listing peers: %v", err)
}
s.logger.Printf("Client '%s' retrieved peers", auth.ClientIdentifier)
peers := []*Peer{}
for _, dp := range devicePeers {
peer := &Peer{
PublicKey: dp.PublicKey.String(),
AllowedIPs: IPNetsToStrings(dp.AllowedIPs),
ReceivedBytes: dp.ReceiveBytes,
TransmittedBytes: dp.TransmitBytes,
LastSeen: dp.LastHandshakeTime.Unix(),
}
peers = append(peers, peer)
}
response := &ListPeersResponse{
Peers: peers,
}
return response, nil
}
// ChangeListenPort updates the listening port wireguard is running on.
// It can be used to allow coordination with a firewall.
func (s *Server) ChangeListenPort(ctx context.Context, request *ChangeListenPortRequest) (*ChangeListenPortResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
s.logger.Printf("Client '%s' changing listen port", auth.ClientIdentifier)
wireguard := &Wireguard{
DeviceName: request.GetDeviceName(),
}
port := int(request.GetListenPort())
if port < 0 || port > maxPort {
return nil, status.Errorf(codes.InvalidArgument, "port must be between 0 and %d", maxPort)
}
err = wireguard.ChangeListenPort(port)
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error changing listen port: %v", err)
}
s.logger.Printf("Client '%s' changed listen port", auth.ClientIdentifier)
response := &ChangeListenPortResponse{
NewListenPort: int32(wireguard.ListenPort),
}
return response, nil
}
// Devices shows all Wireguard interfaces that can be controlled with wgrpcd.
func (s *Server) Devices(ctx context.Context, request *DevicesRequest) (*DevicesResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
s.logger.Printf("Client '%s' looking up devices", auth.ClientIdentifier)
devices, err := Devices()
if err != nil {
return nil, status.Errorf(codes.Internal, "error listing devices: %v", err)
}
s.logger.Printf("Client '%s' looked up devices", auth.ClientIdentifier)
deviceNames := []string{}
for _, device := range devices {
deviceNames = append(deviceNames, device.DeviceName)
}
response := &DevicesResponse{
Devices: deviceNames,
}
return response, nil
}
// Import allows loading new peers into a wgrpcd instance from a list of Peers
func (s *Server) Import(ctx context.Context, request *ImportRequest) (*ImportResponse, error) {
auth, err := s.authResult(ctx)
if err != nil {
return nil, err
}
s.logger.Printf("Client '%s' importing peers", auth.ClientIdentifier)
wireguard, err := New(request.GetDeviceName())
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist: %s", request.GetDeviceName())
}
return nil, status.Errorf(codes.Internal, "error creating peer: %v", err)
}
for _, peer := range request.Peers {
allowedIPs, err := StringsToIPNet(peer.AllowedIPs)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "an ip address in AllowedIPs is invalid, error: %v", err)
}
publicKey, err := wgtypes.ParseKey(peer.PublicKey)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Invalid public key in list: %v", peer.PublicKey)
}
_, err = wireguard.AddNewPeer(allowedIPs, publicKey)
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "that wireguard device does not exist")
}
return nil, status.Errorf(codes.Internal, "error adding peer to wireguard interface: %v", err)
}
}
response := &ImportResponse{}
return response, nil
}
func (s *Server) authResult(ctx context.Context) (*grpcauth.AuthResult, error) {
auth, err := grpcauth.GetAuthResult(ctx)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, err.Error())
}
return auth, nil
}
// NewServer returns a wgrpcd instance configured to use a gRPC server with TLSv1.3.
func NewServer(config *ServerConfig) (*grpc.Server, error) {
// Create a new TLS credentials based on the TLS configuration and return a gRPC server configured with this.
cred := credentials.NewTLS(config.TLSConfig)
var authFunc grpcauth.AuthFunc
var permissionFunc grpcauth.PermissionFunc
if config.AuthFunc != nil {
authFunc = config.AuthFunc
} else {
config.Logger.Printf("WARNING: running wgrpcd using only client certificate auth")
authFunc = NoAuth
permissionFunc = grpcauth.NoPermissions
}
authority := grpcauth.NewAuthority(authFunc, permissionFunc)
rpcServer := grpc.NewServer(
grpc.Creds(cred),
grpc.UnaryInterceptor(authority.UnaryServerInterceptor),
)
RegisterWireguardRPCServer(rpcServer, &Server{logger: config.Logger})
return rpcServer, nil
}