start on wireguard config

Signed-off-by: Evan Hazlett <ejhazlett@gmail.com>
This commit is contained in:
Evan Hazlett 2019-10-04 07:47:16 -04:00
parent f0719ee8a9
commit 2e34c8746e
No known key found for this signature in database
GPG key ID: A519480096146526
11 changed files with 504 additions and 27 deletions

View file

@ -23,6 +23,7 @@ package server
import (
"context"
"crypto/sha256"
"fmt"
"net/url"
"strings"
@ -32,12 +33,13 @@ import (
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/stellarproject/heimdall"
v1 "github.com/stellarproject/heimdall/api/v1"
)
func (s *Server) configureNode() error {
ctx := context.Background()
nodes, err := redis.Strings(s.local(ctx, "KEYS", fmt.Sprintf("%s:*", nodesKey)))
nodes, err := redis.Strings(s.local(ctx, "KEYS", s.getNodeKey("*")))
if err != nil {
return err
}
@ -222,11 +224,75 @@ func (s *Server) updateMasterInfo(ctx context.Context) error {
return nil
}
func (s *Server) updatePeerInfo(ctx context.Context) error {
// check for existing key
endpoint := fmt.Sprintf("%s:%d", heimdall.GetIP(), s.cfg.WireguardPort)
peer, err := s.getPeerInfo(ctx)
if err != nil {
return err
}
// TODO: build allowedIPs from routes and peer network
allowedIPs := []string{s.cfg.PeerNetwork}
ipHash := hashIPs(allowedIPs)
// check cached info and validate
if peer != nil {
peerIPHash := hashIPs(peer.AllowedIPs)
// if endpoint is the same assume unchanged
if peer.Endpoint == endpoint && peerIPHash == ipHash {
logrus.Debugf("peer info: public=%s endpoint=%s", peer.PublicKey, peer.Endpoint)
return nil
}
}
privateKey, publicKey, err := generateWireguardKeys(ctx)
if err != nil {
return err
}
// TODO: allowed IPs
n := &v1.Peer{
PrivateKey: privateKey,
PublicKey: publicKey,
AllowedIPs: allowedIPs,
Endpoint: endpoint,
}
logrus.Debugf("peer info: public=%s endpoint=%s", n.PublicKey, n.Endpoint)
data, err := proto.Marshal(n)
if err != nil {
return err
}
key := s.getPeerKey(s.cfg.ID)
if _, err := s.master(ctx, "SET", key, data); err != nil {
return err
}
return nil
}
func (s *Server) getPeerInfo(ctx context.Context) (*v1.Peer, error) {
key := s.getPeerKey(s.cfg.ID)
data, err := redis.Bytes(s.local(ctx, "GET", key))
if err != nil {
if err == redis.ErrNil {
return nil, nil
}
return nil, err
}
var peer v1.Peer
if err := proto.Unmarshal(data, &peer); err != nil {
return nil, err
}
return &peer, nil
}
func (s *Server) nodeHeartbeat() {
logrus.Debugf("starting node heartbeat: ttl=%s", nodeHeartbeatInterval)
ctx := context.Background()
t := time.NewTicker(nodeHeartbeatInterval)
key := fmt.Sprintf("%s:%s", nodesKey, s.cfg.ID)
key := s.getNodeKey(s.cfg.ID)
for range t.C {
if _, err := s.master(ctx, "SET", key, s.cfg.GRPCAddress); err != nil {
logrus.Error(err)
@ -239,3 +305,11 @@ func (s *Server) nodeHeartbeat() {
}
}
}
func hashIPs(ips []string) string {
h := sha256.New()
for _, ip := range ips {
h.Write([]byte(ip))
}
return fmt.Sprintf("%x", h.Sum(nil))
}

View file

@ -23,6 +23,7 @@ package server
import (
"context"
"fmt"
"io/ioutil"
"runtime"
"runtime/pprof"
@ -43,6 +44,9 @@ const (
clusterKey = "heimdall:key"
nodesKey = "heimdall:nodes"
nodeJoinKey = "heimdall:join"
peersKey = "heimdall:peers"
wireguardConfigPath = "/etc/wireguard/darknet.conf"
)
var (
@ -90,6 +94,7 @@ func (s *Server) GenerateProfile() (string, error) {
}
func (s *Server) Run() error {
ctx := context.Background()
// check peer address and make a grpc request for master info if present
if s.cfg.GRPCPeerAddress != "" {
logrus.Debugf("joining %s", s.cfg.GRPCPeerAddress)
@ -117,6 +122,10 @@ func (s *Server) Run() error {
}
}
if err := s.updatePeerInfo(ctx); err != nil {
return err
}
go s.nodeHeartbeat()
// start listener for pub/sub
@ -161,6 +170,14 @@ func getPool(u string) *redis.Pool {
return pool
}
func (s *Server) getNodeKey(id string) string {
return fmt.Sprintf("%s:%s", nodesKey, id)
}
func (s *Server) getPeerKey(id string) string {
return fmt.Sprintf("%s:%s", peersKey, id)
}
func (s *Server) getClient(addr string) (*client.Client, error) {
return client.NewClient(s.cfg.ID, addr)
}

114
server/wireguard.go Normal file
View file

@ -0,0 +1,114 @@
/*
Copyright 2019 Stellar Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package server
import (
"bytes"
"context"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
v1 "github.com/stellarproject/heimdall/api/v1"
)
const (
defaultInterface = "darknet"
wireguardTemplate = `# managed by heimdall
[Interface]
PrivateKey = {{ .PrivateKey }}
ListenPort = {{ .ListenPort }}
Address = {{ .Address }}
PostUp = iptables -A FORWARD -i {{ .Iface }} -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip6tables -A FORWARD -i {{ .Iface }} -j ACCEPT; ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i {{ .Iface }} -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip6tables -D FORWARD -i {{ .Iface }} -j ACCEPT; ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
{{ range .Peers }}
[Peer]
PublicKey = {{ .PublicKey }}
AllowedIPs = {{ allowedIPs .AllowedIPs }}
Endpoint = {{ .Endpoint }}
{{ end }}
`
)
func allowedIPs(s []string) string {
return strings.Join(s, ", ")
}
type wireguardConfig struct {
Iface string
PrivateKey string
ListenPort int
Address string
Peers []*v1.Peer
}
func generateNodeWireguardConfig(cfg *wireguardConfig) (*os.File, error) {
f, err := ioutil.TempFile("", "heimdall-wireguard-")
if err != nil {
return nil, err
}
t, err := template.New("wireguard").Funcs(template.FuncMap{
"allowedIPs": allowedIPs,
}).Parse(wireguardTemplate)
if err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(wireguardConfigPath), 0755); err != nil {
return nil, err
}
if err := t.Execute(f, cfg); err != nil {
return nil, err
}
f.Close()
return f, nil
}
func generateWireguardKeys(ctx context.Context) (string, string, error) {
kData, err := wg(ctx, nil, "genkey")
if err != nil {
return "", "", err
}
privateKey := strings.TrimSpace(string(kData))
buf := bytes.NewBufferString(privateKey)
pubData, err := wg(ctx, buf, "pubkey")
if err != nil {
return "", "", err
}
publicKey := strings.TrimSpace(string(pubData))
return privateKey, publicKey, nil
}
func wg(ctx context.Context, in io.Reader, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, "wg", args...)
if in != nil {
cmd.Stdin = in
}
return cmd.CombinedOutput()
}

74
server/wireguard_test.go Normal file
View file

@ -0,0 +1,74 @@
/*
Copyright 2019 Stellar Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package server
import (
"io/ioutil"
"os"
"testing"
v1 "github.com/stellarproject/heimdall/api/v1"
)
func TestWireguardTemplate(t *testing.T) {
expectedConf := `# managed by heimdall
[Interface]
PrivateKey = SERVER-PRIVATE-KEY
ListenPort = 10000
Address = 1.2.3.4:10000
PostUp = iptables -A FORWARD -i darknet -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip6tables -A FORWARD -i darknet -j ACCEPT; ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i darknet -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip6tables -D FORWARD -i darknet -j ACCEPT; ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
[Peer]
PublicKey = PEER-PUBLIC-KEY
AllowedIPs = 10.100.0.0/24, 10.254.0.0/16
Endpoint = 100.100.100.100:10000
`
cfg := &wireguardConfig{
Iface: "darknet",
PrivateKey: "SERVER-PRIVATE-KEY",
ListenPort: 10000,
Address: "1.2.3.4:10000",
Peers: []*v1.Peer{
{
PrivateKey: "PEER-PRIVATE-KEY",
PublicKey: "PEER-PUBLIC-KEY",
AllowedIPs: []string{"10.100.0.0/24", "10.254.0.0/16"},
Endpoint: "100.100.100.100:10000",
},
},
}
f, err := generateWireguardConfig(cfg)
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
data, err := ioutil.ReadFile(f.Name())
if err != nil {
t.Fatal(err)
}
if string(data) != expectedConf {
t.Fatalf("config does not match; expected \n %q \n received \n %q", expectedConf, string(data))
}
}