forked from Place1/wg-access-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
184 lines (159 loc) · 5.07 KB
/
main.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
package main
import (
"crypto/rand"
"fmt"
"math"
"net/http"
"net/url"
"os"
"runtime/debug"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"github.com/place1/wg-access-server/proto/proto"
"github.com/gorilla/mux"
"github.com/place1/wg-embed/pkg/wgembed"
"github.com/pkg/errors"
"github.com/place1/wg-access-server/internal/config"
"github.com/place1/wg-access-server/internal/devices"
"github.com/place1/wg-access-server/internal/dnsproxy"
"github.com/place1/wg-access-server/internal/network"
"github.com/place1/wg-access-server/internal/services"
"github.com/place1/wg-access-server/internal/storage"
"github.com/place1/wg-access-server/pkg/authnz"
"github.com/place1/wg-access-server/pkg/authnz/authsession"
"github.com/sirupsen/logrus"
"net/http/httputil"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"google.golang.org/grpc"
)
func main() {
conf := config.Read()
// The server's IP within the VPN virtual network
vpnip := network.ServerVPNIP(conf.VPN.CIDR)
// WireGuard Server
wg, err := wgembed.New(conf.WireGuard.InterfaceName)
if err != nil {
logrus.Fatal(errors.Wrap(err, "failed to create wireguard interface"))
}
defer wg.Close()
logrus.Infof("starting wireguard server on 0.0.0.0:%d", conf.WireGuard.Port)
wg.LoadConfig(&wgembed.ConfigFile{
Interface: wgembed.IfaceConfig{
PrivateKey: conf.WireGuard.PrivateKey,
Address: vpnip.IP.String(),
ListenPort: &conf.WireGuard.Port,
},
})
logrus.Infof("wireguard VPN network is %s", conf.VPN.CIDR)
if err := network.ConfigureForwarding(conf.WireGuard.InterfaceName, conf.VPN.GatewayInterface, conf.VPN.CIDR, *conf.VPN.Rules); err != nil {
logrus.Fatal(err)
}
// DNS Server
if *conf.DNS.Enabled {
dns, err := dnsproxy.New(dnsproxy.DNSServerOpts{
Port: conf.DNS.Port,
Upstream: conf.DNS.Upstream,
})
if err != nil {
logrus.Fatal(errors.Wrap(err, "failed to start dns server"))
}
defer dns.Close()
}
// Storage
var storageDriver storage.Storage
if conf.Storage.Directory != "" {
logrus.Infof("storing data in %s", conf.Storage.Directory)
storageDriver = storage.NewDiskStorage(conf.Storage.Directory)
} else {
storageDriver = storage.NewMemoryStorage()
}
// Services
deviceManager := devices.New(wg.Name(), storageDriver, conf.VPN.CIDR)
if err := deviceManager.StartSync(conf.DisableMetadata); err != nil {
logrus.Fatal(errors.Wrap(err, "failed to sync"))
}
// Router
router := mux.NewRouter()
// if the built website exists, serve that
// otherwise proxy to a local webpack development server
if _, err := os.Stat("website/build"); os.IsNotExist(err) {
u, _ := url.Parse("http://localhost:3000")
router.NotFoundHandler = httputil.NewSingleHostReverseProxy(u)
} else {
router.PathPrefix("/").Handler(http.FileServer(http.Dir("website/build")))
}
// GRPC Server
server := grpc.NewServer([]grpc.ServerOption{
grpc.MaxRecvMsgSize(int(1 * math.Pow(2, 20))), // 1MB
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_logrus.UnaryServerInterceptor(logrus.NewEntry(logrus.StandardLogger())),
grpc_recovery.UnaryServerInterceptor(),
)),
}...)
proto.RegisterServerServer(server, &services.ServerService{
Config: conf,
})
proto.RegisterDevicesServer(server, &services.DeviceService{
DeviceManager: deviceManager,
})
grpcServer := grpcweb.WrapServer(server)
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
logrus.WithField("stack", string(debug.Stack())).Error(err)
}
}()
if grpcServer.IsGrpcWebRequest(r) {
grpcServer.ServeHTTP(w, r)
} else {
if authsession.Authenticated(r.Context()) {
router.ServeHTTP(w, r)
} else {
http.Redirect(w, r, "/signin", http.StatusTemporaryRedirect)
}
}
})
if conf.Auth.IsEnabled() {
handler = authnz.New(conf.Auth, func(user *authsession.Identity) error {
if user.Subject == conf.AdminSubject {
user.Claims.Add("admin", "true")
}
return nil
}).Wrap(handler)
} else {
base := handler
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
base.ServeHTTP(w, r.WithContext(authsession.SetIdentityCtx(r.Context(), &authsession.AuthSession{
Identity: &authsession.Identity{
Subject: "",
},
})))
})
}
publicRouter := mux.NewRouter()
publicRouter.Handle("/health", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
fmt.Fprintf(w, "ok")
})).Methods("GET")
publicRouter.NotFoundHandler = handler
// Listen
address := fmt.Sprintf("0.0.0.0:%d", conf.Port)
srv := &http.Server{
Addr: address,
Handler: publicRouter,
}
// Start Web server
logrus.Infof("web ui listening on %v", address)
if err := srv.ListenAndServe(); err != nil {
logrus.Fatal(errors.Wrap(err, "unable to start http server"))
}
}
func randomBytes(size int) []byte {
blk := make([]byte, size)
_, err := rand.Read(blk)
if err != nil {
logrus.Fatal(err)
}
return blk
}