Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate tailscale into k3s #7352

Merged
merged 1 commit into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .drone.yml
Original file line number Diff line number Diff line change
Expand Up @@ -798,4 +798,4 @@ volumes:
host:
path: /var/run/libvirt/
- name: cache
temp: {}
temp: {}
76 changes: 76 additions & 0 deletions docs/adrs/integrate-vpns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Integrate vpn in k3s

Date: 2023-04-26

## Status

Under review

## Context

There are kubernetes use cases which require a kubernetes cluster to be deployed on a set of heterogeneous nodes, i.e. baremetal nodes, AWS VMs, Azure VMs, etc. Some of these use cases:
* Edge apps which are divided into two parts: a small footprint part deployed at the edge and the "non-edge" part deployed in the DC. These need to be always connected.
* Having a baremetal cluster that requires, only in certain periods, to be extended with hyperscalers VMs to cope out with the demand
* Require cluster to include nodes in different hyperscalers due to resiliency reasons or legal requirements, e.g. GDPR

As of today, k3s allows to deploy a cluster on a set of heterogeneous nodes by a simple and robust solution. This is achieved by using the [websocket proxy](https://github.com/k3s-io/k3s/blob/master/pkg/agent/run.go#L277) to connect the control-plane of the cluster, i.e. kube-api <==> kubelet, and a vpn-type flannel backend, e.g. wireguard, to connect the data-plane, i.e. pod <==> pod/node.

The current solution works well but has a few limitations:
* It requires the server to have a public IP
* It requires the server to open ports on that external IP (e.g. 6443)
* Projects like prometheus or metrics-server that attempt to scrape nodes directly will not work, as pod --> host traffic does not work from scratch
* There is no central management point for your vpn. Therefore, it is impossible to:
1. Have a vpn topology view
2. Monitor node status, performance, etc
3. Configure ACLs or other policies
4. Other features

There are well known projects which can be used as an alternative to our solution. In general, these projects set up a vpn mesh that includes all nodes and thus we could deploy k3s as if all nodes belonged to the same network. Besides, these projects include a central management point that offer extra features and do not require a public IP to be available. Some of these projects are: tailscale, netmaker, nebula or zerotier.

We already have users that are operating k3s on top of one of these vpn solutions. However, it is sometimes a pain for them because they are not necessarily network experts and run into integration problems such as: performance issues due to double encapsulation, [mtu issues due to vpn tunneling encapsulation](https://github.com/k3s-io/k3s/issues/4743), strange errors due to wrong vpn configuration, etc. Moreover, they need to first deploy the vpn, collect important information and then deploy k3s using that information. These three steps are not always easy to automate and automation is paramount in edge use cases.

My proposal is to integrate the best or the two best of these projects into k3s. Integrating in the sense of setting up the vpn and configuring k3s accordingly, so that the user ends up with a working heterogeneous cluster in a matter of seconds by just deploying k3s. At this stage, the proposal is not to incorporate the vpn binaries or daemons inside the k3s binary, we require the user to have the vpn binary installed.

Therefore, the user would have 1 or 2 alternatives to deploy k3s in an heterogeneous cluster:
1 - Our simple and robust solution
2 - vpn solution (e.g. tailscale)
3 - (Optional) vpn solution 2 (e.g. netmaker)

In terms of support, we could always offer support for alternative 1 and best effort support for alternative 2 (or 3). We don't control those projects and some of them have proprietary parts or are using a freemium business model (e.g. lmimited number nodes)

In the first round, only tailscale will be integrated

### Architecture

Going a bit deeper into the code, this is a high-level summary of the changes applied to k3s:
* New flag is passed for both server and agent. This flag provide the name and the auth-keys required for the node to be accepted in the vpn and set node configs (e.g. allow routing of podCIDR via the VPN)
* Functions that start the vpn and provide information of its status in "package netutil" (pkg/netutil/vpn.go)
* VPNInfo struct in "package netutil" that includes important vpn endpoint information such as the vpn endpoint IP and the nodeID in the vpn context (for config purposes)
* The collection of vpn endpoint information and its start are implemented by calling the vpn binary. Tailscale has a "not-feature-complete" go client but netmaker does not, so calls to the binary is the common denominator
* In the agents, if a vpn config flag is detected, the vpn is started before the websocket proxy is created, so the agent can contact the server
* In the servers, if a vpn config flag is detected, the vpn is started before the apiserver is started, so that agents can contact the server. AdvertiseIP is changed to use the VPN IP
* If a vpn config flag is detected, the vpn info is collected and the nodeIP replaced before the kubelet certificate is created (due to SAN). This happens in func get(...) of pkg/agent/config/config.go
* A flannel backend is defined: tailscale. These use the general purpose "extension" backend, which executes shell commands when certain events happen (e.g. new node is added)
* When a new node is added, flannel queries the subnet podCIDR for that node. The new backends, by executing the vpn binary with certain flags, allow traffic to/from that subnet podCIDR to flow via the VPN
* In HA scenarios, etcd IP will not use the VPN IP (serverConfig.ControlConfig.PrivateIP) but the main interface. Running etcd traffic over the internet does not make sense. Therefore, k3s-HA over VPN is not supported


## Decision

???

## Consequences

Good
====
* Users can automatically deploy vpn+k3s in seconds that seamlessly work and connect heterogeneous nodes
* New exciting feature for the community
* We offer not only our simple solution but some extra ones for heterogeneous clusters
* Fills the gap for useful use cases in edge

Bad
===
* Integration with 3rd party projects which we do not control and thus complete support is not possible (similar to CNI plugins)
* Some of these projects are not 100% open source (e.g. tailscale) and some are in its infancy (i.e. buggy), e.g. netmaker.
* Not possible to configure a set of heterogeneous nodes in Rancher Management. Therefore, it is currently impossible to deploy through it but could be deployed standalone

29 changes: 29 additions & 0 deletions pkg/agent/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/k3s-io/k3s/pkg/daemons/control/deps"
"github.com/k3s-io/k3s/pkg/util"
"github.com/k3s-io/k3s/pkg/version"
"github.com/k3s-io/k3s/pkg/vpn"
"github.com/pkg/errors"
"github.com/rancher/wrangler/pkg/slice"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -382,6 +383,29 @@ func get(ctx context.Context, envInfo *cmds.Agent, proxy proxy.Proxy) (*config.N
return nil, err
}

// If there is a VPN, we must overwrite NodeIP and flannel interface
var vpnInfo vpn.VPNInfo
if envInfo.VPNAuth != "" {
vpnInfo, err = vpn.GetVPNInfo(envInfo.VPNAuth)
if err != nil {
return nil, err
}
if len(vpnInfo.IPs) != 0 {
logrus.Infof("Node-ip changed to %v due to VPN", vpnInfo.IPs)
if len(envInfo.NodeIP) != 0 {
logrus.Warn("VPN provider overrides configured node-ip parameter")
}
if len(envInfo.NodeExternalIP) != 0 {
logrus.Warn("VPN provider overrides node-external-ip parameter")
}
nodeIPs = vpnInfo.IPs
flannelIface, err = net.InterfaceByName(vpnInfo.VPNInterface)
if err != nil {
return nil, errors.Wrapf(err, "unable to find vpn interface: %s", vpnInfo.VPNInterface)
}
}
}

nodeExternalIPs, err := util.ParseStringSliceToIPs(envInfo.NodeExternalIP)
if err != nil {
return nil, fmt.Errorf("invalid node-external-ip: %w", err)
Expand Down Expand Up @@ -532,6 +556,11 @@ func get(ctx context.Context, envInfo *cmds.Agent, proxy proxy.Proxy) (*config.N
nodeConfig.AgentConfig.CNIBinDir = filepath.Dir(hostLocal)
nodeConfig.AgentConfig.CNIConfDir = filepath.Join(envInfo.DataDir, "agent", "etc", "cni", "net.d")
nodeConfig.AgentConfig.FlannelCniConfFile = envInfo.FlannelCniConfFile

// It does not make sense to use VPN without its flannel backend
if envInfo.VPNAuth != "" {
nodeConfig.FlannelBackend = vpnInfo.ProviderName
}
}

if nodeConfig.Docker {
Expand Down
19 changes: 19 additions & 0 deletions pkg/agent/flannel/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ const (
"PSK": "%psk%"
}`

tailscaledBackend = `{
"Type": "extension",
"PostStartupCommand": "tailscale up --accept-routes --advertise-routes=%Routes%",
"ShutdownCommand": "tailscale down"
}`

wireguardNativeBackend = `{
"Type": "wireguard",
"PersistentKeepaliveInterval": %PersistentKeepaliveInterval%,
Expand Down Expand Up @@ -216,6 +222,19 @@ func createFlannelConf(nodeConfig *config.Node) error {
backendConf = hostGWBackend
case config.FlannelBackendIPSEC:
logrus.Fatal("The ipsec backend is deprecated and was removed in k3s v1.27; please switch to wireguard-native. Check our docs for information on how to migrate.")
case config.FlannelBackendTailscale:
var routes string
switch netMode {
case ipv4:
routes = "$SUBNET"
case (ipv4 + ipv6):
routes = "$SUBNET,$IPV6SUBNET"
case ipv6:
routes = "$IPV6SUBNET"
default:
return fmt.Errorf("incorrect netMode for flannel tailscale backend")
}
backendConf = strings.ReplaceAll(tailscaledBackend, "%Routes%", routes)
case config.FlannelBackendWireguardNative:
mode, ok := backendOptions["Mode"]
if !ok {
Expand Down
18 changes: 16 additions & 2 deletions pkg/cli/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import (
"github.com/k3s-io/k3s/pkg/agent"
"github.com/k3s-io/k3s/pkg/cli/cmds"
"github.com/k3s-io/k3s/pkg/datadir"
"github.com/k3s-io/k3s/pkg/token"
"github.com/k3s-io/k3s/pkg/util"
"github.com/k3s-io/k3s/pkg/version"
"github.com/k3s-io/k3s/pkg/vpn"
"github.com/rancher/wrangler/pkg/signals"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
Expand All @@ -40,7 +40,7 @@ func Run(ctx *cli.Context) error {
}

if cmds.AgentConfig.TokenFile != "" {
token, err := token.ReadFile(cmds.AgentConfig.TokenFile)
token, err := util.ReadFile(cmds.AgentConfig.TokenFile)
if err != nil {
return err
}
Expand Down Expand Up @@ -77,6 +77,20 @@ func Run(ctx *cli.Context) error {
contextCtx := signals.SetupSignalContext()

go cmds.WriteCoverage(contextCtx)
if cmds.AgentConfig.VPNAuthFile != "" {
cmds.AgentConfig.VPNAuth, err = util.ReadFile(cmds.AgentConfig.VPNAuthFile)
if err != nil {
return err
}
}

// Starts the VPN in the agent if config was set up
if cmds.AgentConfig.VPNAuth != "" {
err := vpn.StartVPN(cmds.AgentConfig.VPNAuth)
if err != nil {
return err
}
}

return agent.Run(contextCtx, cfg)
}
16 changes: 16 additions & 0 deletions pkg/cli/cmds/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ type Agent struct {
FlannelIface string
FlannelConf string
FlannelCniConfFile string
VPNAuth string
VPNAuthFile string
Debug bool
Rootless bool
RootlessAlreadyUnshared bool
Expand Down Expand Up @@ -151,6 +153,18 @@ var (
Usage: "(agent/networking) Override default flannel cni config file",
Destination: &AgentConfig.FlannelCniConfFile,
}
VPNAuth = &cli.StringFlag{
Name: "vpn-auth",
Usage: "(agent/networking) (experimental) Credentials for the VPN provider. It must include the provider name and join key in the format name=<vpn-provider>,joinKey=<key>",
EnvVar: version.ProgramUpper + "_VPN_AUTH",
Destination: &AgentConfig.VPNAuth,
}
VPNAuthFile = &cli.StringFlag{
Name: "vpn-auth-file",
Usage: "(agent/networking) (experimental) File containing credentials for the VPN provider. It must include the provider name and join key in the format name=<vpn-provider>,joinKey=<key>",
EnvVar: version.ProgramUpper + "_VPN_AUTH_FILE",
Destination: &AgentConfig.VPNAuthFile,
}
ResolvConfFlag = &cli.StringFlag{
Name: "resolv-conf",
Usage: "(agent/networking) Kubelet resolv.conf file",
Expand Down Expand Up @@ -254,6 +268,8 @@ func NewAgentCommand(action func(ctx *cli.Context) error) cli.Command {
PreferBundledBin,
// Deprecated/hidden below
DockerFlag,
VPNAuth,
VPNAuthFile,
},
}
}
2 changes: 2 additions & 0 deletions pkg/cli/cmds/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,8 @@ var ServerFlags = []cli.Flag{
FlannelIfaceFlag,
FlannelConfFlag,
FlannelCniConfFileFlag,
VPNAuth,
VPNAuthFile,
ExtraKubeletArgs,
ExtraKubeProxyArgs,
ProtectKernelDefaultsFlag,
Expand Down
52 changes: 42 additions & 10 deletions pkg/cli/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ import (
"github.com/k3s-io/k3s/pkg/etcd"
"github.com/k3s-io/k3s/pkg/rootless"
"github.com/k3s-io/k3s/pkg/server"
"github.com/k3s-io/k3s/pkg/token"
"github.com/k3s-io/k3s/pkg/util"
"github.com/k3s-io/k3s/pkg/version"
"github.com/k3s-io/k3s/pkg/vpn"
"github.com/pkg/errors"
"github.com/rancher/wrangler/pkg/signals"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -90,6 +90,21 @@ func run(app *cli.Context, cfg *cmds.Server, leaderControllers server.CustomCont
}
}

if cmds.AgentConfig.VPNAuthFile != "" {
cmds.AgentConfig.VPNAuth, err = util.ReadFile(cmds.AgentConfig.VPNAuthFile)
if err != nil {
return err
}
}

// Starts the VPN in the server if config was set up
if cmds.AgentConfig.VPNAuth != "" {
err := vpn.StartVPN(cmds.AgentConfig.VPNAuth)
if err != nil {
return err
}
}

agentReady := make(chan struct{})

serverConfig := server.Config{}
Expand All @@ -99,13 +114,13 @@ func run(app *cli.Context, cfg *cmds.Server, leaderControllers server.CustomCont
serverConfig.ControlConfig.AgentToken = cfg.AgentToken
serverConfig.ControlConfig.JoinURL = cfg.ServerURL
if cfg.AgentTokenFile != "" {
serverConfig.ControlConfig.AgentToken, err = token.ReadFile(cfg.AgentTokenFile)
serverConfig.ControlConfig.AgentToken, err = util.ReadFile(cfg.AgentTokenFile)
if err != nil {
return err
}
}
if cfg.TokenFile != "" {
serverConfig.ControlConfig.Token, err = token.ReadFile(cfg.TokenFile)
serverConfig.ControlConfig.Token, err = util.ReadFile(cfg.TokenFile)
if err != nil {
return err
}
Expand Down Expand Up @@ -207,14 +222,31 @@ func run(app *cli.Context, cfg *cmds.Server, leaderControllers server.CustomCont
serverConfig.ControlConfig.PrivateIP = util.GetFirstValidIPString(cmds.AgentConfig.NodeIP)
}

// if not set, try setting advertise-ip from agent node-external-ip
if serverConfig.ControlConfig.AdvertiseIP == "" && len(cmds.AgentConfig.NodeExternalIP) != 0 {
serverConfig.ControlConfig.AdvertiseIP = util.GetFirstValidIPString(cmds.AgentConfig.NodeExternalIP)
}
// if not set, try setting advertise-ip from agent VPN
if cmds.AgentConfig.VPNAuth != "" {
vpnInfo, err := vpn.GetVPNInfo(cmds.AgentConfig.VPNAuth)
if err != nil {
return err
}
if len(vpnInfo.IPs) != 0 {
logrus.Infof("Advertise-address changed to %v due to VPN", vpnInfo.IPs)
if serverConfig.ControlConfig.AdvertiseIP != "" {
logrus.Warn("Conflict in the config detected. VPN integration overwrites advertise-address but the config is setting the advertise-address parameter")
}
serverConfig.ControlConfig.AdvertiseIP = vpnInfo.IPs[0].String()
}
logrus.Warn("Etcd IP (PrivateIP) remains the local IP. Running etcd traffic over VPN is not recommended due to performance issues")
} else {

// if not set, try setting advertise-ip from agent node-ip
if serverConfig.ControlConfig.AdvertiseIP == "" && len(cmds.AgentConfig.NodeIP) != 0 {
serverConfig.ControlConfig.AdvertiseIP = util.GetFirstValidIPString(cmds.AgentConfig.NodeIP)
// if not set, try setting advertise-ip from agent node-external-ip
if serverConfig.ControlConfig.AdvertiseIP == "" && len(cmds.AgentConfig.NodeExternalIP) != 0 {
serverConfig.ControlConfig.AdvertiseIP = util.GetFirstValidIPString(cmds.AgentConfig.NodeExternalIP)
}

// if not set, try setting advertise-ip from agent node-ip
if serverConfig.ControlConfig.AdvertiseIP == "" && len(cmds.AgentConfig.NodeIP) != 0 {
serverConfig.ControlConfig.AdvertiseIP = util.GetFirstValidIPString(cmds.AgentConfig.NodeIP)
}
}

// if we ended up with any advertise-ips, ensure they're added to the SAN list;
Expand Down
4 changes: 2 additions & 2 deletions pkg/cluster/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"io"
"strings"

"github.com/k3s-io/k3s/pkg/token"
"github.com/k3s-io/k3s/pkg/util"
"golang.org/x/crypto/pbkdf2"
)

Expand All @@ -32,7 +32,7 @@ func keyHash(passphrase string) string {
// encrypt encrypts a byte slice using aes+gcm with a pbkdf2 key derived from the passphrase and a random salt.
// It returns a byte slice containing the salt and base64-encoded ciphertext.
func encrypt(passphrase string, plaintext []byte) ([]byte, error) {
salt, err := token.Random(8)
salt, err := util.Random(8)
if err != nil {
return nil, err
}
Expand Down
1 change: 1 addition & 0 deletions pkg/daemons/config/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const (
FlannelBackendHostGW = "host-gw"
FlannelBackendIPSEC = "ipsec"
FlannelBackendWireguardNative = "wireguard-native"
FlannelBackendTailscale = "tailscale"
rbrtbnfgl marked this conversation as resolved.
Show resolved Hide resolved
EgressSelectorModeAgent = "agent"
EgressSelectorModeCluster = "cluster"
EgressSelectorModeDisabled = "disabled"
Expand Down
5 changes: 2 additions & 3 deletions pkg/daemons/control/deps/deps.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"github.com/k3s-io/k3s/pkg/cloudprovider"
"github.com/k3s-io/k3s/pkg/daemons/config"
"github.com/k3s-io/k3s/pkg/passwd"
"github.com/k3s-io/k3s/pkg/token"
"github.com/k3s-io/k3s/pkg/util"
"github.com/k3s-io/k3s/pkg/version"
certutil "github.com/rancher/dynamiclistener/cert"
Expand Down Expand Up @@ -272,7 +271,7 @@ func genEncryptedNetworkInfo(controlConfig *config.Control) error {
return nil
}

psk, err := token.Random(ipsecTokenSize)
psk, err := util.Random(ipsecTokenSize)
if err != nil {
return err
}
Expand All @@ -291,7 +290,7 @@ func getServerPass(passwd *passwd.Passwd, config *config.Control) (string, error
serverPass, _ = passwd.Pass("server")
}
if serverPass == "" {
serverPass, err = token.Random(16)
serverPass, err = util.Random(16)
if err != nil {
return "", err
}
Expand Down
Loading