Skip to content

Commit

Permalink
Wireguard Tunnel Container
Browse files Browse the repository at this point in the history
  • Loading branch information
cheina97 committed Oct 4, 2023
1 parent c101f15 commit 5ca9e1d
Show file tree
Hide file tree
Showing 17 changed files with 864 additions and 48 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ on:
- network-general
- network-external
- network-internal
- frc/wgtunnel
repository_dispatch:
types:
- test-command
Expand Down Expand Up @@ -90,6 +91,7 @@ jobs:
- metric-agent
- telemetry
- proxy
- gateway/tunnel/wireguard
steps:

- name: Set up QEMU
Expand Down
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ rbacs: controller-gen
$(CONTROLLER_GEN) paths="./cmd/uninstaller" rbac:roleName=liqo-pre-delete output:rbac:stdout | awk -v RS="---\n" 'NR>1{f="./deployments/liqo/files/liqo-pre-delete-" $$4 ".yaml";printf "%s",$$0 > f; close(f)}' && sed -i -n '/rules/,$$p' deployments/liqo/files/liqo-pre-delete-ClusterRole.yaml
$(CONTROLLER_GEN) paths="./cmd/metric-agent" rbac:roleName=liqo-metric-agent output:rbac:stdout | awk -v RS="---\n" 'NR>1{f="./deployments/liqo/files/liqo-metric-agent-" $$4 ".yaml";printf "%s",$$0 > f; close(f)}' && sed -i -n '/rules/,$$p' deployments/liqo/files/liqo-metric-agent-ClusterRole.yaml
$(CONTROLLER_GEN) paths="./cmd/telemetry" rbac:roleName=liqo-telemetry output:rbac:stdout | awk -v RS="---\n" 'NR>1{f="./deployments/liqo/files/liqo-telemetry-" $$4 ".yaml";printf "%s",$$0 > f; close(f)}' && sed -i -n '/rules/,$$p' deployments/liqo/files/liqo-telemetry-ClusterRole.yaml
$(CONTROLLER_GEN) paths="./pkg/gateway/..." rbac:roleName=liqo-gateway output:rbac:stdout | awk -v RS="---\n" 'NR>1{f="./deployments/liqo/files/liqo-gateway-" $$4 ".yaml";printf "%s",$$0 > f; close(f)}' && sed -i -n '/rules/,$$p' deployments/liqo/files/liqo-gateway-ClusterRole.yaml

# Install gci if not available
gci:
Expand Down
7 changes: 5 additions & 2 deletions apis/networking/v1alpha1/publickey_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.

// PublicKeyResource the name of the publickey resources.
var PublicKeyResource = "publickeys"
var PublicKeyResource = "publickeies"

// PublicKeyKind is the kind name used to register the PublicKey CRD.
var PublicKeyKind = "PublicKey"
Expand All @@ -40,8 +40,11 @@ type PublicKeySpec struct {
PublicKey []byte `json:"publicKey,omitempty"`
}

// publickeies is used for resource name pluralization because k8s api do not manage false friends.
// Waiting for this fix https://github.com/kubernetes-sigs/kubebuilder/pull/3408

// +kubebuilder:object:root=true
// +kubebuilder:resource:categories=liqo
// +kubebuilder:resource:categories=liqo,path=publickeies

// PublicKey contains a public key data required by some interconnection technologies.
type PublicKey struct {
Expand Down
20 changes: 20 additions & 0 deletions build/gateway/tunnel/wireguard/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM golang:1.21 as goBuilder
WORKDIR /tmp/builder

COPY go.mod ./go.mod
COPY go.sum ./go.sum
RUN go mod download

COPY . ./
RUN CGO_ENABLED=0 GOOS=linux GOARCH=$(go env GOARCH) go build -ldflags="-s -w" ./cmd/gateway/tunnel/wireguard


FROM alpine:3.18

RUN apk update && \
apk add iptables bash wireguard-tools tcpdump conntrack-tools curl && \
rm -rf /var/cache/apk/*

COPY --from=goBuilder /tmp/builder/wireguard /usr/bin/liqo-wireguard

CMD [ "/usr/bin/wireguard" ]
146 changes: 146 additions & 0 deletions cmd/gateway/tunnel/wireguard/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Copyright 2019-2023 The Liqo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package wireguard contains the logic to configure the Wireguard interface.
package main

import (
"flag"
"net"
"os"

"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/log"

ipamv1alpha1 "github.com/liqotech/liqo/apis/ipam/v1alpha1"
networkingv1alpha1 "github.com/liqotech/liqo/apis/networking/v1alpha1"
"github.com/liqotech/liqo/pkg/gateway/tunnel/wireguard"
"github.com/liqotech/liqo/pkg/utils/mapper"
"github.com/liqotech/liqo/pkg/utils/restcfg"
)

var (
addToSchemeFunctions = []func(*runtime.Scheme) error{
networkingv1alpha1.AddToScheme,
ipamv1alpha1.AddToScheme,
}
)

func main() {
var err error
ctx := ctrl.SetupSignalHandler()
options := wireguard.Options{}
scheme := runtime.NewScheme()

// Init flags and check mandatory ones.
restcfg.InitFlags(nil)
klog.InitFlags(nil)
wireguard.InitFlags(&options)
flag.Parse()
if err = wireguard.CheckMandatoryFlags(wireguard.MandatoryFlags); err != nil {
klog.Errorf("Mandatory flags: %v", err)
os.Exit(1)
}

// Adds the APIs to the scheme.
for _, addToScheme := range addToSchemeFunctions {
if err = addToScheme(scheme); err != nil {
klog.Errorf("unable to add scheme: %v", err)
os.Exit(1)
}
}

// Set controller-runtime logger.
log.SetLogger(klog.NewKlogr())

// Get the rest config.
cfg := config.GetConfigOrDie()

// Create the client. This cliend should be used only outside the reconciler.
cl, err := client.New(cfg, client.Options{
Cache: nil,
})
if err != nil {
klog.Errorf("unable to create client: %v", err)
os.Exit(1)
}

// Create the manager.
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
MapperProvider: mapper.LiqoMapperProvider(scheme),
Scheme: scheme,
Namespace: options.Namespace,
MetricsBindAddress: options.MetricsAddress,
HealthProbeBindAddress: options.ProbeAddr,
LeaderElection: options.LeaderElection,
LeaderElectionID: "66cf253f.wgtunnel.liqo.io",
LeaderElectionNamespace: options.Namespace,
LeaderElectionReleaseOnCancel: true,
LeaderElectionResourceLock: resourcelock.LeasesResourceLock,
})
if err != nil {
klog.Error(err)
os.Exit(1)
}

// Setup the controller.
pkr, err := wireguard.NewPublicKeysReconciler(
mgr.GetClient(),
mgr.GetScheme(),
mgr.GetEventRecorderFor("wireguard-controller"),
&options,
)
if err != nil {
klog.Error(err)
os.Exit(1)
}

dnsChan := make(chan event.GenericEvent)
if wireguard.IsDNSRoutineRequired(&options) {
go wireguard.StartDNSRoutine(ctx, dnsChan, &options)
} else {
options.EndpointIP = net.ParseIP(options.EndpointAddress)
}

// Setup the controller.
if err = pkr.SetupWithManager(mgr, dnsChan); err != nil {
klog.Error(err)
os.Exit(1)
}

// Ensure presence of Secret with private and public keys.
if err = wireguard.EnsureKeysSecret(ctx, cl, &options); err != nil {
klog.Error(err)
os.Exit(1)
}

/* // Create the wg-liqo interface and init the wireguard configuration depending on the mode (client/server).
err = wireguard.InitWireguardLink(&options)
if err != nil {
klog.Errorf("unable to create wireguard interface: %v", err)
os.Exit(1)
} */

// Start the manager.
if err = mgr.Start(ctx); err != nil {
klog.Error(err)
os.Exit(1)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
controller-gen.kubebuilder.io/version: v0.13.0
name: publickeies.networking.liqo.io
spec:
group: networking.liqo.io
names:
categories:
- liqo
kind: PublicKey
listKind: PublicKeyList
plural: publickeies
singular: publickey
scope: Namespaced
versions:
- name: v1alpha1
schema:
openAPIV3Schema:
description: PublicKey contains a public key data required by some interconnection
technologies.
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to the latest
internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
type: object
spec:
description: PublicKeySpec defines the desired state of PublicKey.
properties:
publicKey:
description: PublicKey contains the public key.
format: byte
type: string
type: object
type: object
served: true
storage: true
49 changes: 3 additions & 46 deletions deployments/liqo/files/liqo-gateway-ClusterRole.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,20 @@ rules:
- apiGroups:
- ""
resources:
- events
- secrets
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
- patch
- update
- watch
- apiGroups:
- ""
resources:
- services
verbs:
- list
- patch
- update
- watch
- apiGroups:
- net.liqo.io
- networking.liqo.io
resources:
- natmappings
- publickeys
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- net.liqo.io
resources:
- tunnelendpoints
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- net.liqo.io
resources:
- tunnelendpoints/status
verbs:
- get
- patch
- update
54 changes: 54 additions & 0 deletions pkg/gateway/tunnel/wireguard/device.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2019-2023 The Liqo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package wireguard

import (
"net"

"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)

func configureServerDevice(wgcl *wgctrl.Client, options *Options, peerPubKey wgtypes.Key) error {
return wgcl.ConfigureDevice(WireguardInterfaceName, wgtypes.Config{
PrivateKey: &options.PrivateKey,
ListenPort: &options.ListenPort,
Peers: []wgtypes.PeerConfig{
{
PublicKey: peerPubKey,
},
},
})
}

// Runs in a goroutine.
func configureClientDevice(wgcl *wgctrl.Client, options *Options, peerPubKey wgtypes.Key) error {
options.EndpointIPMutex.Lock()
defer options.EndpointIPMutex.Unlock()

return wgcl.ConfigureDevice(WireguardInterfaceName, wgtypes.Config{
PrivateKey: &options.PrivateKey,
Peers: []wgtypes.PeerConfig{
{
PublicKey: peerPubKey,
AllowedIPs: []net.IPNet{{IP: net.IP{0, 0, 0, 0}, Mask: net.CIDRMask(0, 32)}},
Endpoint: &net.UDPAddr{
IP: options.EndpointIP,
Port: options.EndpointPort,
},
},
},
})
}
Loading

0 comments on commit 5ca9e1d

Please sign in to comment.