main.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build linux
  4. // The containerboot binary is a wrapper for starting tailscaled in a container.
  5. // It handles reading the desired mode of operation out of environment
  6. // variables, bringing up and authenticating Tailscale, and any other
  7. // kubernetes-specific side jobs.
  8. //
  9. // As with most container things, configuration is passed through environment
  10. // variables. All configuration is optional.
  11. //
  12. // - TS_AUTHKEY: the authkey to use for login.
  13. // - TS_HOSTNAME: the hostname to request for the node.
  14. // - TS_ROUTES: subnet routes to advertise. Explicitly setting it to an empty
  15. // value will cause containerboot to stop acting as a subnet router for any
  16. // previously advertised routes. To accept routes, use TS_EXTRA_ARGS to pass
  17. // in --accept-routes.
  18. // - TS_DEST_IP: proxy all incoming Tailscale traffic to the given
  19. // destination defined by an IP address.
  20. // - TS_EXPERIMENTAL_DEST_DNS_NAME: proxy all incoming Tailscale traffic to the given
  21. // destination defined by a DNS name. The DNS name will be periodically resolved and firewall rules updated accordingly.
  22. // This is currently intended to be used by the Kubernetes operator (ExternalName Services).
  23. // This is an experimental env var and will likely change in the future.
  24. // - TS_TAILNET_TARGET_IP: proxy all incoming non-Tailscale traffic to the given
  25. // destination defined by an IP.
  26. // - TS_TAILNET_TARGET_FQDN: proxy all incoming non-Tailscale traffic to the given
  27. // destination defined by a MagicDNS name.
  28. // - TS_TAILSCALED_EXTRA_ARGS: extra arguments to 'tailscaled'.
  29. // - TS_EXTRA_ARGS: extra arguments to 'tailscale up'.
  30. // - TS_USERSPACE: run with userspace networking (the default)
  31. // instead of kernel networking.
  32. // - TS_STATE_DIR: the directory in which to store tailscaled
  33. // state. The data should persist across container
  34. // restarts.
  35. // - TS_ACCEPT_DNS: whether to use the tailnet's DNS configuration.
  36. // - TS_KUBE_SECRET: the name of the Kubernetes secret in which to
  37. // store tailscaled state.
  38. // - TS_SOCKS5_SERVER: the address on which to listen for SOCKS5
  39. // proxying into the tailnet.
  40. // - TS_OUTBOUND_HTTP_PROXY_LISTEN: the address on which to listen
  41. // for HTTP proxying into the tailnet.
  42. // - TS_SOCKET: the path where the tailscaled LocalAPI socket should
  43. // be created.
  44. // - TS_AUTH_ONCE: if true, only attempt to log in if not already
  45. // logged in. If false (the default, for backwards
  46. // compatibility), forcibly log in every time the
  47. // container starts.
  48. // - TS_SERVE_CONFIG: if specified, is the file path where the ipn.ServeConfig is located.
  49. // It will be applied once tailscaled is up and running. If the file contains
  50. // ${TS_CERT_DOMAIN}, it will be replaced with the value of the available FQDN.
  51. // It cannot be used in conjunction with TS_DEST_IP. The file is watched for changes,
  52. // and will be re-applied when it changes.
  53. // - TS_HEALTHCHECK_ADDR_PORT: deprecated, use TS_ENABLE_HEALTH_CHECK instead and optionally
  54. // set TS_LOCAL_ADDR_PORT. Will be removed in 1.82.0.
  55. // - TS_LOCAL_ADDR_PORT: the address and port to serve local metrics and health
  56. // check endpoints if enabled via TS_ENABLE_METRICS and/or TS_ENABLE_HEALTH_CHECK.
  57. // Defaults to [::]:9002, serving on all available interfaces.
  58. // - TS_ENABLE_METRICS: if true, a metrics endpoint will be served at /metrics on
  59. // the address specified by TS_LOCAL_ADDR_PORT. See https://tailscale.com/kb/1482/client-metrics
  60. // for more information on the metrics exposed.
  61. // - TS_ENABLE_HEALTH_CHECK: if true, a health check endpoint will be served at /healthz on
  62. // the address specified by TS_LOCAL_ADDR_PORT. The health endpoint will return 200
  63. // OK if this node has at least one tailnet IP address, otherwise returns 503.
  64. // NB: the health criteria might change in the future.
  65. // - TS_EXPERIMENTAL_VERSIONED_CONFIG_DIR: if specified, a path to a
  66. // directory that containers tailscaled config in file. The config file needs to be
  67. // named cap-<current-tailscaled-cap>.hujson. If this is set, TS_HOSTNAME,
  68. // TS_EXTRA_ARGS, TS_AUTHKEY,
  69. // TS_ROUTES, TS_ACCEPT_DNS env vars must not be set. If this is set,
  70. // containerboot only runs `tailscaled --config <path-to-this-configfile>`
  71. // and not `tailscale up` or `tailscale set`.
  72. // The config file contents are currently read once on container start.
  73. // NB: This env var is currently experimental and the logic will likely change!
  74. // TS_EXPERIMENTAL_ENABLE_FORWARDING_OPTIMIZATIONS: set to true to
  75. // autoconfigure the default network interface for optimal performance for
  76. // Tailscale subnet router/exit node.
  77. // https://tailscale.com/kb/1320/performance-best-practices#linux-optimizations-for-subnet-routers-and-exit-nodes
  78. // NB: This env var is currently experimental and the logic will likely change!
  79. // - EXPERIMENTAL_ALLOW_PROXYING_CLUSTER_TRAFFIC_VIA_INGRESS: if set to true
  80. // and if this containerboot instance is an L7 ingress proxy (created by
  81. // the Kubernetes operator), set up rules to allow proxying cluster traffic,
  82. // received on the Pod IP of this node, to the ingress target in the cluster.
  83. // This, in conjunction with MagicDNS name resolution in cluster, can be
  84. // useful for cases where a cluster workload needs to access a target in
  85. // cluster using the same hostname (in this case, the MagicDNS name of the ingress proxy)
  86. // as a non-cluster workload on tailnet.
  87. // This is only meant to be configured by the Kubernetes operator.
  88. //
  89. // When running on Kubernetes, containerboot defaults to storing state in the
  90. // "tailscale" kube secret. To store state on local disk instead, set
  91. // TS_KUBE_SECRET="" and TS_STATE_DIR=/path/to/storage/dir. The state dir should
  92. // be persistent storage.
  93. //
  94. // Additionally, if TS_AUTHKEY is not set and the TS_KUBE_SECRET contains an
  95. // "authkey" field, that key is used as the tailscale authkey.
  96. package main
  97. import (
  98. "context"
  99. "errors"
  100. "fmt"
  101. "io/fs"
  102. "log"
  103. "math"
  104. "net"
  105. "net/http"
  106. "net/netip"
  107. "os"
  108. "os/signal"
  109. "path/filepath"
  110. "slices"
  111. "strings"
  112. "sync"
  113. "sync/atomic"
  114. "syscall"
  115. "time"
  116. "golang.org/x/sys/unix"
  117. "tailscale.com/client/tailscale"
  118. "tailscale.com/ipn"
  119. kubeutils "tailscale.com/k8s-operator"
  120. healthz "tailscale.com/kube/health"
  121. "tailscale.com/kube/kubetypes"
  122. "tailscale.com/kube/metrics"
  123. "tailscale.com/kube/services"
  124. "tailscale.com/tailcfg"
  125. "tailscale.com/types/logger"
  126. "tailscale.com/types/ptr"
  127. "tailscale.com/util/deephash"
  128. "tailscale.com/util/linuxfw"
  129. )
  130. func newNetfilterRunner(logf logger.Logf) (linuxfw.NetfilterRunner, error) {
  131. if defaultBool("TS_TEST_FAKE_NETFILTER", false) {
  132. return linuxfw.NewFakeIPTablesRunner(), nil
  133. }
  134. return linuxfw.New(logf, "")
  135. }
  136. func main() {
  137. if err := run(); err != nil && !errors.Is(err, context.Canceled) {
  138. log.Fatal(err)
  139. }
  140. }
  141. func run() error {
  142. log.SetPrefix("boot: ")
  143. tailscale.I_Acknowledge_This_API_Is_Unstable = true
  144. cfg, err := configFromEnv()
  145. if err != nil {
  146. return fmt.Errorf("invalid configuration: %w", err)
  147. }
  148. if !cfg.UserspaceMode {
  149. if err := ensureTunFile(cfg.Root); err != nil {
  150. return fmt.Errorf("unable to create tuntap device file: %w", err)
  151. }
  152. if cfg.ProxyTargetIP != "" || cfg.ProxyTargetDNSName != "" || cfg.Routes != nil || cfg.TailnetTargetIP != "" || cfg.TailnetTargetFQDN != "" {
  153. if err := ensureIPForwarding(cfg.Root, cfg.ProxyTargetIP, cfg.TailnetTargetIP, cfg.TailnetTargetFQDN, cfg.Routes); err != nil {
  154. log.Printf("Failed to enable IP forwarding: %v", err)
  155. log.Printf("To run tailscale as a proxy or router container, IP forwarding must be enabled.")
  156. if cfg.InKubernetes {
  157. return fmt.Errorf("you can either set the sysctls as a privileged initContainer, or run the tailscale container with privileged=true.")
  158. } else {
  159. return fmt.Errorf("you can fix this by running the container with privileged=true, or the equivalent in your container runtime that permits access to sysctls.")
  160. }
  161. }
  162. }
  163. }
  164. // Root context for the whole containerboot process, used to make sure
  165. // shutdown signals are promptly and cleanly handled.
  166. ctx, cancel := contextWithExitSignalWatch()
  167. defer cancel()
  168. // bootCtx is used for all setup stuff until we're in steady
  169. // state, so that if something is hanging we eventually time out
  170. // and crashloop the container.
  171. bootCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
  172. defer cancel()
  173. var kc *kubeClient
  174. if cfg.InKubernetes {
  175. kc, err = newKubeClient(cfg.Root, cfg.KubeSecret)
  176. if err != nil {
  177. return fmt.Errorf("error initializing kube client: %w", err)
  178. }
  179. if err := cfg.setupKube(bootCtx, kc); err != nil {
  180. return fmt.Errorf("error setting up for running on Kubernetes: %w", err)
  181. }
  182. // Clear out any state from previous runs of containerboot. Check
  183. // hasKubeStateStore because although we know we're in kube, that
  184. // doesn't guarantee the state store is properly configured.
  185. if hasKubeStateStore(cfg) {
  186. if err := kc.resetContainerbootState(bootCtx, cfg.PodUID); err != nil {
  187. return fmt.Errorf("error clearing previous state from Secret: %w", err)
  188. }
  189. }
  190. }
  191. client, daemonProcess, err := startTailscaled(bootCtx, cfg)
  192. if err != nil {
  193. return fmt.Errorf("failed to bring up tailscale: %w", err)
  194. }
  195. killTailscaled := func() {
  196. // The default termination grace period for a Pod is 30s. We wait 25s at
  197. // most so that we still reserve some of that budget for tailscaled
  198. // to receive and react to a SIGTERM before the SIGKILL that k8s
  199. // will send at the end of the grace period.
  200. ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
  201. defer cancel()
  202. if err := services.EnsureServicesNotAdvertised(ctx, client, log.Printf); err != nil {
  203. log.Printf("Error ensuring services are not advertised: %v", err)
  204. }
  205. if hasKubeStateStore(cfg) {
  206. // Check we're not shutting tailscaled down while it's still writing
  207. // state. If we authenticate and fail to write all the state, we'll
  208. // never recover automatically.
  209. log.Printf("Checking for consistent state")
  210. err := kc.waitForConsistentState(ctx)
  211. if err != nil {
  212. log.Printf("Error waiting for consistent state on shutdown: %v", err)
  213. }
  214. }
  215. log.Printf("Sending SIGTERM to tailscaled")
  216. if err := daemonProcess.Signal(unix.SIGTERM); err != nil {
  217. log.Fatalf("error shutting tailscaled down: %v", err)
  218. }
  219. }
  220. defer killTailscaled()
  221. var healthCheck *healthz.Healthz
  222. ep := &egressProxy{}
  223. if cfg.HealthCheckAddrPort != "" {
  224. mux := http.NewServeMux()
  225. log.Printf("Running healthcheck endpoint at %s/healthz", cfg.HealthCheckAddrPort)
  226. healthCheck = healthz.RegisterHealthHandlers(mux, cfg.PodIPv4, log.Printf)
  227. close := runHTTPServer(mux, cfg.HealthCheckAddrPort)
  228. defer close()
  229. }
  230. if cfg.localMetricsEnabled() || cfg.localHealthEnabled() || cfg.egressSvcsTerminateEPEnabled() {
  231. mux := http.NewServeMux()
  232. if cfg.localMetricsEnabled() {
  233. log.Printf("Running metrics endpoint at %s/metrics", cfg.LocalAddrPort)
  234. metrics.RegisterMetricsHandlers(mux, client, cfg.DebugAddrPort)
  235. }
  236. if cfg.localHealthEnabled() {
  237. log.Printf("Running healthcheck endpoint at %s/healthz", cfg.LocalAddrPort)
  238. healthCheck = healthz.RegisterHealthHandlers(mux, cfg.PodIPv4, log.Printf)
  239. }
  240. if cfg.egressSvcsTerminateEPEnabled() {
  241. log.Printf("Running egress preshutdown hook at %s%s", cfg.LocalAddrPort, kubetypes.EgessServicesPreshutdownEP)
  242. ep.registerHandlers(mux)
  243. }
  244. close := runHTTPServer(mux, cfg.LocalAddrPort)
  245. defer close()
  246. }
  247. if cfg.EnableForwardingOptimizations {
  248. if err := client.SetUDPGROForwarding(bootCtx); err != nil {
  249. log.Printf("[unexpected] error enabling UDP GRO forwarding: %v", err)
  250. }
  251. }
  252. w, err := client.WatchIPNBus(bootCtx, ipn.NotifyInitialNetMap|ipn.NotifyInitialPrefs|ipn.NotifyInitialState)
  253. if err != nil {
  254. return fmt.Errorf("failed to watch tailscaled for updates: %w", err)
  255. }
  256. // Now that we've started tailscaled, we can symlink the socket to the
  257. // default location if needed.
  258. const defaultTailscaledSocketPath = "/var/run/tailscale/tailscaled.sock"
  259. if cfg.Socket != "" && cfg.Socket != defaultTailscaledSocketPath {
  260. // If we were given a socket path, symlink it to the default location so
  261. // that the CLI can find it without any extra flags.
  262. // See #6849.
  263. dir := filepath.Dir(defaultTailscaledSocketPath)
  264. err := os.MkdirAll(dir, 0700)
  265. if err == nil {
  266. err = syscall.Symlink(cfg.Socket, defaultTailscaledSocketPath)
  267. }
  268. if err != nil {
  269. log.Printf("[warning] failed to symlink socket: %v\n\tTo interact with the Tailscale CLI please use `tailscale --socket=%q`", err, cfg.Socket)
  270. }
  271. }
  272. // Because we're still shelling out to `tailscale up` to get access to its
  273. // flag parser, we have to stop watching the IPN bus so that we can block on
  274. // the subcommand without stalling anything. Then once it's done, we resume
  275. // watching the bus.
  276. //
  277. // Depending on the requested mode of operation, this auth step happens at
  278. // different points in containerboot's lifecycle, hence the helper function.
  279. didLogin := false
  280. authTailscale := func() error {
  281. if didLogin {
  282. return nil
  283. }
  284. didLogin = true
  285. w.Close()
  286. if err := tailscaleUp(bootCtx, cfg); err != nil {
  287. return fmt.Errorf("failed to auth tailscale: %w", err)
  288. }
  289. w, err = client.WatchIPNBus(bootCtx, ipn.NotifyInitialNetMap|ipn.NotifyInitialState)
  290. if err != nil {
  291. return fmt.Errorf("rewatching tailscaled for updates after auth: %w", err)
  292. }
  293. return nil
  294. }
  295. if isTwoStepConfigAlwaysAuth(cfg) {
  296. if err := authTailscale(); err != nil {
  297. return fmt.Errorf("failed to auth tailscale: %w", err)
  298. }
  299. }
  300. authLoop:
  301. for {
  302. n, err := w.Next()
  303. if err != nil {
  304. return fmt.Errorf("failed to read from tailscaled: %w", err)
  305. }
  306. if n.State != nil {
  307. switch *n.State {
  308. case ipn.NeedsLogin:
  309. if isOneStepConfig(cfg) {
  310. // This could happen if this is the first time tailscaled was run for this
  311. // device and the auth key was not passed via the configfile.
  312. return fmt.Errorf("invalid state: tailscaled daemon started with a config file, but tailscale is not logged in: ensure you pass a valid auth key in the config file.")
  313. }
  314. if err := authTailscale(); err != nil {
  315. return fmt.Errorf("failed to auth tailscale: %w", err)
  316. }
  317. case ipn.NeedsMachineAuth:
  318. log.Printf("machine authorization required, please visit the admin panel")
  319. case ipn.Running:
  320. // Technically, all we want is to keep monitoring the bus for
  321. // netmap updates. However, in order to make the container crash
  322. // if tailscale doesn't initially come up, the watch has a
  323. // startup deadline on it. So, we have to break out of this
  324. // watch loop, cancel the watch, and watch again with no
  325. // deadline to continue monitoring for changes.
  326. break authLoop
  327. default:
  328. log.Printf("tailscaled in state %q, waiting", *n.State)
  329. }
  330. }
  331. }
  332. w.Close()
  333. if isTwoStepConfigAuthOnce(cfg) {
  334. // Now that we are authenticated, we can set/reset any of the
  335. // settings that we need to.
  336. if err := tailscaleSet(ctx, cfg); err != nil {
  337. return fmt.Errorf("failed to auth tailscale: %w", err)
  338. }
  339. }
  340. // Remove any serve config and advertised HTTPS endpoint that may have been set by a previous run of
  341. // containerboot, but only if we're providing a new one.
  342. if cfg.ServeConfigPath != "" {
  343. log.Printf("serve proxy: unsetting previous config")
  344. if err := client.SetServeConfig(ctx, new(ipn.ServeConfig)); err != nil {
  345. return fmt.Errorf("failed to unset serve config: %w", err)
  346. }
  347. }
  348. if hasKubeStateStore(cfg) && isTwoStepConfigAuthOnce(cfg) {
  349. // We were told to only auth once, so any secret-bound
  350. // authkey is no longer needed. We don't strictly need to
  351. // wipe it, but it's good hygiene.
  352. log.Printf("Deleting authkey from kube secret")
  353. if err := kc.deleteAuthKey(ctx); err != nil {
  354. return fmt.Errorf("deleting authkey from kube secret: %w", err)
  355. }
  356. }
  357. w, err = client.WatchIPNBus(ctx, ipn.NotifyInitialNetMap|ipn.NotifyInitialState)
  358. if err != nil {
  359. return fmt.Errorf("rewatching tailscaled for updates after auth: %w", err)
  360. }
  361. // If tailscaled config was read from a mounted file, watch the file for updates and reload.
  362. cfgWatchErrChan := make(chan error)
  363. if cfg.TailscaledConfigFilePath != "" {
  364. go watchTailscaledConfigChanges(ctx, cfg.TailscaledConfigFilePath, client, cfgWatchErrChan)
  365. }
  366. var (
  367. startupTasksDone = false
  368. currentIPs deephash.Sum // tailscale IPs assigned to device
  369. currentDeviceID deephash.Sum // device ID
  370. currentDeviceEndpoints deephash.Sum // device FQDN and IPs
  371. currentEgressIPs deephash.Sum
  372. addrs []netip.Prefix
  373. backendAddrs []net.IP
  374. certDomain = new(atomic.Pointer[string])
  375. certDomainChanged = make(chan bool, 1)
  376. triggerWatchServeConfigChanges sync.Once
  377. )
  378. var nfr linuxfw.NetfilterRunner
  379. if isL3Proxy(cfg) {
  380. nfr, err = newNetfilterRunner(log.Printf)
  381. if err != nil {
  382. return fmt.Errorf("error creating new netfilter runner: %w", err)
  383. }
  384. }
  385. // Setup for proxies that are configured to proxy to a target specified
  386. // by a DNS name (TS_EXPERIMENTAL_DEST_DNS_NAME).
  387. const defaultCheckPeriod = time.Minute * 10 // how often to check what IPs the DNS name resolves to
  388. var (
  389. tc = make(chan string, 1)
  390. failedResolveAttempts int
  391. t *time.Timer = time.AfterFunc(defaultCheckPeriod, func() {
  392. if cfg.ProxyTargetDNSName != "" {
  393. tc <- "recheck"
  394. }
  395. })
  396. )
  397. // egressSvcsErrorChan will get an error sent to it if this containerboot instance is configured to expose 1+
  398. // egress services in HA mode and errored.
  399. egressSvcsErrorChan := make(chan error)
  400. ingressSvcsErrorChan := make(chan error)
  401. defer t.Stop()
  402. // resetTimer resets timer for when to next attempt to resolve the DNS
  403. // name for the proxy configured with TS_EXPERIMENTAL_DEST_DNS_NAME. The
  404. // timer gets reset to 10 minutes from now unless the last resolution
  405. // attempt failed. If one or more consecutive previous resolution
  406. // attempts failed, the next resolution attempt will happen after the smallest
  407. // of (10 minutes, 2 ^ number-of-consecutive-failed-resolution-attempts
  408. // seconds) i.e 2s, 4s, 8s ... 10 minutes.
  409. resetTimer := func(lastResolveFailed bool) {
  410. if !lastResolveFailed {
  411. log.Printf("reconfigureTimer: next DNS resolution attempt in %s", defaultCheckPeriod)
  412. t.Reset(defaultCheckPeriod)
  413. failedResolveAttempts = 0
  414. return
  415. }
  416. minDelay := 2 // 2 seconds
  417. nextTick := time.Second * time.Duration(math.Pow(float64(minDelay), float64(failedResolveAttempts)))
  418. if nextTick > defaultCheckPeriod {
  419. nextTick = defaultCheckPeriod // cap at 10 minutes
  420. }
  421. log.Printf("reconfigureTimer: last DNS resolution attempt failed, next DNS resolution attempt in %v", nextTick)
  422. t.Reset(nextTick)
  423. failedResolveAttempts++
  424. }
  425. var egressSvcsNotify chan ipn.Notify
  426. notifyChan := make(chan ipn.Notify)
  427. errChan := make(chan error)
  428. go func() {
  429. for {
  430. n, err := w.Next()
  431. if err != nil {
  432. errChan <- err
  433. break
  434. } else {
  435. notifyChan <- n
  436. }
  437. }
  438. }()
  439. var wg sync.WaitGroup
  440. runLoop:
  441. for {
  442. select {
  443. case <-ctx.Done():
  444. // Although killTailscaled() is deferred earlier, if we
  445. // have started the reaper defined below, we need to
  446. // kill tailscaled and let reaper clean up child
  447. // processes.
  448. killTailscaled()
  449. break runLoop
  450. case err := <-errChan:
  451. return fmt.Errorf("failed to read from tailscaled: %w", err)
  452. case err := <-cfgWatchErrChan:
  453. return fmt.Errorf("failed to watch tailscaled config: %w", err)
  454. case n := <-notifyChan:
  455. if n.State != nil && *n.State != ipn.Running {
  456. // Something's gone wrong and we've left the authenticated state.
  457. // Our container image never recovered gracefully from this, and the
  458. // control flow required to make it work now is hard. So, just crash
  459. // the container and rely on the container runtime to restart us,
  460. // whereupon we'll go through initial auth again.
  461. return fmt.Errorf("tailscaled left running state (now in state %q), exiting", *n.State)
  462. }
  463. if n.NetMap != nil {
  464. addrs = n.NetMap.SelfNode.Addresses().AsSlice()
  465. newCurrentIPs := deephash.Hash(&addrs)
  466. ipsHaveChanged := newCurrentIPs != currentIPs
  467. // Store device ID in a Kubernetes Secret before
  468. // setting up any routing rules. This ensures
  469. // that, for containerboot instances that are
  470. // Kubernetes operator proxies, the operator is
  471. // able to retrieve the device ID from the
  472. // Kubernetes Secret to clean up tailnet nodes
  473. // for proxies whose route setup continuously
  474. // fails.
  475. deviceID := n.NetMap.SelfNode.StableID()
  476. if hasKubeStateStore(cfg) && deephash.Update(&currentDeviceID, &deviceID) {
  477. if err := kc.storeDeviceID(ctx, n.NetMap.SelfNode.StableID()); err != nil {
  478. return fmt.Errorf("storing device ID in Kubernetes Secret: %w", err)
  479. }
  480. }
  481. if cfg.TailnetTargetFQDN != "" {
  482. var (
  483. egressAddrs []netip.Prefix
  484. newCurentEgressIPs deephash.Sum
  485. egressIPsHaveChanged bool
  486. node tailcfg.NodeView
  487. nodeFound bool
  488. )
  489. for _, n := range n.NetMap.Peers {
  490. if strings.EqualFold(n.Name(), cfg.TailnetTargetFQDN) {
  491. node = n
  492. nodeFound = true
  493. break
  494. }
  495. }
  496. if !nodeFound {
  497. log.Printf("Tailscale node %q not found; it either does not exist, or not reachable because of ACLs", cfg.TailnetTargetFQDN)
  498. break
  499. }
  500. egressAddrs = node.Addresses().AsSlice()
  501. newCurentEgressIPs = deephash.Hash(&egressAddrs)
  502. egressIPsHaveChanged = newCurentEgressIPs != currentEgressIPs
  503. // The firewall rules get (re-)installed:
  504. // - on startup
  505. // - when the tailnet IPs of the tailnet target have changed
  506. // - when the tailnet IPs of this node have changed
  507. if (egressIPsHaveChanged || ipsHaveChanged) && len(egressAddrs) != 0 {
  508. var rulesInstalled bool
  509. for _, egressAddr := range egressAddrs {
  510. ea := egressAddr.Addr()
  511. if ea.Is4() || (ea.Is6() && nfr.HasIPV6NAT()) {
  512. rulesInstalled = true
  513. log.Printf("Installing forwarding rules for destination %v", ea.String())
  514. if err := installEgressForwardingRule(ctx, ea.String(), addrs, nfr); err != nil {
  515. return fmt.Errorf("installing egress proxy rules for destination %s: %v", ea.String(), err)
  516. }
  517. }
  518. }
  519. if !rulesInstalled {
  520. return fmt.Errorf("no forwarding rules for egress addresses %v, host supports IPv6: %v", egressAddrs, nfr.HasIPV6NAT())
  521. }
  522. }
  523. currentEgressIPs = newCurentEgressIPs
  524. }
  525. if cfg.ProxyTargetIP != "" && len(addrs) != 0 && ipsHaveChanged {
  526. log.Printf("Installing proxy rules")
  527. if err := installIngressForwardingRule(ctx, cfg.ProxyTargetIP, addrs, nfr); err != nil {
  528. return fmt.Errorf("installing ingress proxy rules: %w", err)
  529. }
  530. }
  531. if cfg.ProxyTargetDNSName != "" && len(addrs) != 0 && ipsHaveChanged {
  532. newBackendAddrs, err := resolveDNS(ctx, cfg.ProxyTargetDNSName)
  533. if err != nil {
  534. log.Printf("[unexpected] error resolving DNS name %s: %v", cfg.ProxyTargetDNSName, err)
  535. resetTimer(true)
  536. continue
  537. }
  538. backendsHaveChanged := !(slices.EqualFunc(backendAddrs, newBackendAddrs, func(ip1 net.IP, ip2 net.IP) bool {
  539. return slices.ContainsFunc(newBackendAddrs, func(ip net.IP) bool { return ip.Equal(ip1) })
  540. }))
  541. if backendsHaveChanged {
  542. log.Printf("installing ingress proxy rules for backends %v", newBackendAddrs)
  543. if err := installIngressForwardingRuleForDNSTarget(ctx, newBackendAddrs, addrs, nfr); err != nil {
  544. return fmt.Errorf("error installing ingress proxy rules: %w", err)
  545. }
  546. }
  547. resetTimer(false)
  548. backendAddrs = newBackendAddrs
  549. }
  550. if cfg.ServeConfigPath != "" {
  551. cd := certDomainFromNetmap(n.NetMap)
  552. if cd == "" {
  553. cd = kubetypes.ValueNoHTTPS
  554. }
  555. prev := certDomain.Swap(ptr.To(cd))
  556. if prev == nil || *prev != cd {
  557. select {
  558. case certDomainChanged <- true:
  559. default:
  560. }
  561. }
  562. }
  563. if cfg.TailnetTargetIP != "" && ipsHaveChanged && len(addrs) != 0 {
  564. log.Printf("Installing forwarding rules for destination %v", cfg.TailnetTargetIP)
  565. if err := installEgressForwardingRule(ctx, cfg.TailnetTargetIP, addrs, nfr); err != nil {
  566. return fmt.Errorf("installing egress proxy rules: %w", err)
  567. }
  568. }
  569. // If this is a L7 cluster ingress proxy (set up
  570. // by Kubernetes operator) and proxying of
  571. // cluster traffic to the ingress target is
  572. // enabled, set up proxy rule each time the
  573. // tailnet IPs of this node change (including
  574. // the first time they become available).
  575. if cfg.AllowProxyingClusterTrafficViaIngress && cfg.ServeConfigPath != "" && ipsHaveChanged && len(addrs) != 0 {
  576. log.Printf("installing rules to forward traffic for %s to node's tailnet IP", cfg.PodIP)
  577. if err := installTSForwardingRuleForDestination(ctx, cfg.PodIP, addrs, nfr); err != nil {
  578. return fmt.Errorf("installing rules to forward traffic to node's tailnet IP: %w", err)
  579. }
  580. }
  581. currentIPs = newCurrentIPs
  582. // Only store device FQDN and IP addresses to
  583. // Kubernetes Secret when any required proxy
  584. // route setup has succeeded. IPs and FQDN are
  585. // read from the Secret by the Tailscale
  586. // Kubernetes operator and, for some proxy
  587. // types, such as Tailscale Ingress, advertized
  588. // on the Ingress status. Writing them to the
  589. // Secret only after the proxy routing has been
  590. // set up ensures that the operator does not
  591. // advertize endpoints of broken proxies.
  592. // TODO (irbekrm): instead of using the IP and FQDN, have some other mechanism for the proxy signal that it is 'Ready'.
  593. deviceEndpoints := []any{n.NetMap.SelfNode.Name(), n.NetMap.SelfNode.Addresses()}
  594. if hasKubeStateStore(cfg) && deephash.Update(&currentDeviceEndpoints, &deviceEndpoints) {
  595. if err := kc.storeDeviceEndpoints(ctx, n.NetMap.SelfNode.Name(), n.NetMap.SelfNode.Addresses().AsSlice()); err != nil {
  596. return fmt.Errorf("storing device IPs and FQDN in Kubernetes Secret: %w", err)
  597. }
  598. }
  599. if healthCheck != nil {
  600. healthCheck.Update(len(addrs) != 0)
  601. }
  602. if cfg.ServeConfigPath != "" {
  603. triggerWatchServeConfigChanges.Do(func() {
  604. go watchServeConfigChanges(ctx, certDomainChanged, certDomain, client, kc, cfg)
  605. })
  606. }
  607. if egressSvcsNotify != nil {
  608. egressSvcsNotify <- n
  609. }
  610. }
  611. if !startupTasksDone {
  612. // For containerboot instances that act as TCP proxies (proxying traffic to an endpoint
  613. // passed via one of the env vars that containerboot reads) and store state in a
  614. // Kubernetes Secret, we consider startup tasks done at the point when device info has
  615. // been successfully stored to state Secret. For all other containerboot instances, if
  616. // we just get to this point the startup tasks can be considered done.
  617. if !isL3Proxy(cfg) || !hasKubeStateStore(cfg) || (currentDeviceEndpoints != deephash.Sum{} && currentDeviceID != deephash.Sum{}) {
  618. // This log message is used in tests to detect when all
  619. // post-auth configuration is done.
  620. log.Println("Startup complete, waiting for shutdown signal")
  621. startupTasksDone = true
  622. // Configure egress proxy. Egress proxy will set up firewall rules to proxy
  623. // traffic to tailnet targets configured in the provided configuration file. It
  624. // will then continuously monitor the config file and netmap updates and
  625. // reconfigure the firewall rules as needed. If any of its operations fail, it
  626. // will crash this node.
  627. if cfg.EgressProxiesCfgPath != "" {
  628. log.Printf("configuring egress proxy using configuration file at %s", cfg.EgressProxiesCfgPath)
  629. egressSvcsNotify = make(chan ipn.Notify)
  630. opts := egressProxyRunOpts{
  631. cfgPath: cfg.EgressProxiesCfgPath,
  632. nfr: nfr,
  633. kc: kc,
  634. tsClient: client,
  635. stateSecret: cfg.KubeSecret,
  636. netmapChan: egressSvcsNotify,
  637. podIPv4: cfg.PodIPv4,
  638. tailnetAddrs: addrs,
  639. }
  640. go func() {
  641. if err := ep.run(ctx, n, opts); err != nil {
  642. egressSvcsErrorChan <- err
  643. }
  644. }()
  645. }
  646. ip := ingressProxy{}
  647. if cfg.IngressProxiesCfgPath != "" {
  648. log.Printf("configuring ingress proxy using configuration file at %s", cfg.IngressProxiesCfgPath)
  649. opts := ingressProxyOpts{
  650. cfgPath: cfg.IngressProxiesCfgPath,
  651. nfr: nfr,
  652. kc: kc,
  653. stateSecret: cfg.KubeSecret,
  654. podIPv4: cfg.PodIPv4,
  655. podIPv6: cfg.PodIPv6,
  656. }
  657. go func() {
  658. if err := ip.run(ctx, opts); err != nil {
  659. ingressSvcsErrorChan <- err
  660. }
  661. }()
  662. }
  663. // Wait on tailscaled process. It won't be cleaned up by default when the
  664. // container exits as it is not PID1. TODO (irbekrm): perhaps we can replace the
  665. // reaper by a running cmd.Wait in a goroutine immediately after starting
  666. // tailscaled?
  667. reaper := func() {
  668. defer wg.Done()
  669. for {
  670. var status unix.WaitStatus
  671. _, err := unix.Wait4(daemonProcess.Pid, &status, 0, nil)
  672. if errors.Is(err, unix.EINTR) {
  673. continue
  674. }
  675. if err != nil {
  676. log.Fatalf("Waiting for tailscaled to exit: %v", err)
  677. }
  678. log.Print("tailscaled exited")
  679. os.Exit(0)
  680. }
  681. }
  682. wg.Add(1)
  683. go reaper()
  684. }
  685. }
  686. case <-tc:
  687. newBackendAddrs, err := resolveDNS(ctx, cfg.ProxyTargetDNSName)
  688. if err != nil {
  689. log.Printf("[unexpected] error resolving DNS name %s: %v", cfg.ProxyTargetDNSName, err)
  690. resetTimer(true)
  691. continue
  692. }
  693. backendsHaveChanged := !(slices.EqualFunc(backendAddrs, newBackendAddrs, func(ip1 net.IP, ip2 net.IP) bool {
  694. return slices.ContainsFunc(newBackendAddrs, func(ip net.IP) bool { return ip.Equal(ip1) })
  695. }))
  696. if backendsHaveChanged && len(addrs) != 0 {
  697. log.Printf("Backend address change detected, installing proxy rules for backends %v", newBackendAddrs)
  698. if err := installIngressForwardingRuleForDNSTarget(ctx, newBackendAddrs, addrs, nfr); err != nil {
  699. return fmt.Errorf("installing ingress proxy rules for DNS target %s: %v", cfg.ProxyTargetDNSName, err)
  700. }
  701. }
  702. backendAddrs = newBackendAddrs
  703. resetTimer(false)
  704. case e := <-egressSvcsErrorChan:
  705. return fmt.Errorf("egress proxy failed: %v", e)
  706. case e := <-ingressSvcsErrorChan:
  707. return fmt.Errorf("ingress proxy failed: %v", e)
  708. }
  709. }
  710. wg.Wait()
  711. return nil
  712. }
  713. // ensureTunFile checks that /dev/net/tun exists, creating it if
  714. // missing.
  715. func ensureTunFile(root string) error {
  716. // Verify that /dev/net/tun exists, in some container envs it
  717. // needs to be mknod-ed.
  718. if _, err := os.Stat(filepath.Join(root, "dev/net")); errors.Is(err, fs.ErrNotExist) {
  719. if err := os.MkdirAll(filepath.Join(root, "dev/net"), 0755); err != nil {
  720. return err
  721. }
  722. }
  723. if _, err := os.Stat(filepath.Join(root, "dev/net/tun")); errors.Is(err, fs.ErrNotExist) {
  724. dev := unix.Mkdev(10, 200) // tuntap major and minor
  725. if err := unix.Mknod(filepath.Join(root, "dev/net/tun"), 0600|unix.S_IFCHR, int(dev)); err != nil {
  726. return err
  727. }
  728. }
  729. return nil
  730. }
  731. func resolveDNS(ctx context.Context, name string) ([]net.IP, error) {
  732. // TODO (irbekrm): look at using recursive.Resolver instead to resolve
  733. // the DNS names as well as retrieve TTLs. It looks though that this
  734. // seems to return very short TTLs (shorter than on the actual records).
  735. ip4s, err := net.DefaultResolver.LookupIP(ctx, "ip4", name)
  736. if err != nil {
  737. if e, ok := err.(*net.DNSError); !(ok && e.IsNotFound) {
  738. return nil, fmt.Errorf("error looking up IPv4 addresses: %w", err)
  739. }
  740. }
  741. ip6s, err := net.DefaultResolver.LookupIP(ctx, "ip6", name)
  742. if err != nil {
  743. if e, ok := err.(*net.DNSError); !(ok && e.IsNotFound) {
  744. return nil, fmt.Errorf("error looking up IPv6 addresses: %w", err)
  745. }
  746. }
  747. if len(ip4s) == 0 && len(ip6s) == 0 {
  748. return nil, fmt.Errorf("no IPv4 or IPv6 addresses found for host: %s", name)
  749. }
  750. return append(ip4s, ip6s...), nil
  751. }
  752. // contextWithExitSignalWatch watches for SIGTERM/SIGINT signals. It returns a
  753. // context that gets cancelled when a signal is received and a cancel function
  754. // that can be called to free the resources when the watch should be stopped.
  755. func contextWithExitSignalWatch() (context.Context, func()) {
  756. closeChan := make(chan struct{})
  757. ctx, cancel := context.WithCancel(context.Background())
  758. signalChan := make(chan os.Signal, 1)
  759. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  760. go func() {
  761. select {
  762. case <-signalChan:
  763. cancel()
  764. case <-closeChan:
  765. return
  766. }
  767. }()
  768. closeOnce := sync.Once{}
  769. f := func() {
  770. closeOnce.Do(func() {
  771. close(closeChan)
  772. })
  773. }
  774. return ctx, f
  775. }
  776. // tailscaledConfigFilePath returns the path to the tailscaled config file that
  777. // should be used for the current capability version. It is determined by the
  778. // TS_EXPERIMENTAL_VERSIONED_CONFIG_DIR environment variable and looks for a
  779. // file named cap-<capability_version>.hujson in the directory. It searches for
  780. // the highest capability version that is less than or equal to the current
  781. // capability version.
  782. func tailscaledConfigFilePath() string {
  783. dir := os.Getenv("TS_EXPERIMENTAL_VERSIONED_CONFIG_DIR")
  784. if dir == "" {
  785. return ""
  786. }
  787. fe, err := os.ReadDir(dir)
  788. if err != nil {
  789. log.Fatalf("error reading tailscaled config directory %q: %v", dir, err)
  790. }
  791. maxCompatVer := tailcfg.CapabilityVersion(-1)
  792. for _, e := range fe {
  793. // We don't check if type if file as in most cases this will
  794. // come from a mounted kube Secret, where the directory contents
  795. // will be various symlinks.
  796. if e.Type().IsDir() {
  797. continue
  798. }
  799. cv, err := kubeutils.CapVerFromFileName(e.Name())
  800. if err != nil {
  801. continue
  802. }
  803. if cv > maxCompatVer && cv <= tailcfg.CurrentCapabilityVersion {
  804. maxCompatVer = cv
  805. }
  806. }
  807. if maxCompatVer == -1 {
  808. log.Fatalf("no tailscaled config file found in %q for current capability version %d", dir, tailcfg.CurrentCapabilityVersion)
  809. }
  810. filePath := filepath.Join(dir, kubeutils.TailscaledConfigFileName(maxCompatVer))
  811. log.Printf("Using tailscaled config file %q to match current capability version %d", filePath, tailcfg.CurrentCapabilityVersion)
  812. return filePath
  813. }
  814. func runHTTPServer(mux *http.ServeMux, addr string) (close func() error) {
  815. ln, err := net.Listen("tcp", addr)
  816. if err != nil {
  817. log.Fatalf("failed to listen on addr %q: %v", addr, err)
  818. }
  819. srv := &http.Server{Handler: mux}
  820. go func() {
  821. if err := srv.Serve(ln); err != nil {
  822. if err != http.ErrServerClosed {
  823. log.Fatalf("failed running server: %v", err)
  824. } else {
  825. log.Printf("HTTP server at %s closed", addr)
  826. }
  827. }
  828. }()
  829. return func() error {
  830. err := srv.Shutdown(context.Background())
  831. return errors.Join(err, ln.Close())
  832. }
  833. }