wireguard.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package docker
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/api/types/container"
  8. "github.com/docker/docker/client"
  9. "goseg/config"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. // "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  15. )
  16. func LoadWireguard() error {
  17. logger.Info("Loading Startram Wireguard container")
  18. confPath := filepath.Join(config.BasePath, "settings", "wireguard.json")
  19. _, err := os.Open(confPath)
  20. if err != nil {
  21. // create a default if it doesn't exist
  22. err = config.CreateDefaultWGConf()
  23. if err != nil {
  24. // error if we can't create it
  25. errmsg := fmt.Sprintf("Unable to create WG config! %v", err)
  26. logger.Error(errmsg)
  27. panic(errmsg)
  28. }
  29. }
  30. logger.Info("Running Wireguard")
  31. info, err := StartContainer("wireguard", "wireguard")
  32. if err != nil {
  33. logger.Error(fmt.Sprintf("Error starting wireguard: %v", err))
  34. return err
  35. }
  36. config.UpdateContainerState("wireguard", info)
  37. return nil
  38. }
  39. // wireguard container config builder
  40. func wgContainerConf() (container.Config, container.HostConfig, error) {
  41. var containerConfig container.Config
  42. var hostConfig container.HostConfig
  43. // construct the container metadata from version server info
  44. containerInfo, err := GetLatestContainerInfo("wireguard")
  45. if err != nil {
  46. return containerConfig, hostConfig, err
  47. }
  48. desiredTag := containerInfo["tag"]
  49. desiredHash := containerInfo["hash"]
  50. desiredRepo := containerInfo["repo"]
  51. desiredImage := fmt.Sprintf("%s:%s@sha256:%s", desiredRepo, desiredTag, desiredHash)
  52. // construct the container config struct
  53. containerConfig = container.Config{
  54. Image: desiredImage,
  55. Entrypoint: []string{"/bin/bash"},
  56. Tty: true,
  57. OpenStdin: true,
  58. }
  59. // always on wg nw
  60. hostConfig = container.HostConfig{
  61. NetworkMode: "container:wireguard",
  62. }
  63. return containerConfig, hostConfig, nil
  64. }
  65. // wg client config builder
  66. func buildWgConf() (string, error) {
  67. confB64 := config.StartramConfig.Conf
  68. confBytes, err := base64.StdEncoding.DecodeString(confB64)
  69. if err != nil {
  70. return "", fmt.Errorf("Failed to decode remote WG base64: %v", err)
  71. }
  72. conf := string(confBytes)
  73. configData := config.Conf()
  74. res := strings.Replace(conf, "privkey", configData.Privkey, -1)
  75. return res, nil
  76. }
  77. func writeWgConf() error {
  78. newConf, err := buildWgConf()
  79. if err != nil {
  80. return err
  81. }
  82. filePath := filepath.Join(config.DockerDir, "settings", "wireguard", "_data", "wg0.conf")
  83. existingConf, err := ioutil.ReadFile(filePath)
  84. if err != nil {
  85. // assume it doesn't exist, so write the current config
  86. return writeWgConfToFile(filePath, newConf)
  87. }
  88. if string(existingConf) != newConf {
  89. // If they differ, overwrite
  90. return writeWgConfToFile(filePath, newConf)
  91. }
  92. return nil
  93. }
  94. func writeWgConfToFile(filePath string, content string) error {
  95. err := ioutil.WriteFile(filePath, []byte(content), 0644)
  96. if err != nil {
  97. return fmt.Errorf("Failed to write new WG config: %v", err)
  98. }
  99. // Copy to volume
  100. err = copyFileToVolume(filePath, "/etc/wireguard/", "wireguard")
  101. if err != nil {
  102. return fmt.Errorf("Failed to copy WG config file to volume: %v", err)
  103. }
  104. return nil
  105. }
  106. // write wg conf to volume
  107. func copyFileToVolume(filePath string, targetPath string, volumeName string) error {
  108. ctx := context.Background()
  109. cli, err := client.NewClientWithOpts(client.FromEnv)
  110. if err != nil {
  111. return err
  112. }
  113. // temp container to mount
  114. resp, err := cli.ContainerCreate(ctx, &container.Config{
  115. Image: "busybox",
  116. Cmd: []string{"tail", "-f", "/dev/null"},
  117. }, &container.HostConfig{
  118. Binds: []string{volumeName + ":" + targetPath},
  119. }, nil, nil, "bb_temp")
  120. if err != nil {
  121. return err
  122. }
  123. if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
  124. return err
  125. }
  126. file, err := os.Open(filepath.Join(filePath))
  127. if err != nil {
  128. return fmt.Errorf("failed to open wg0 file: %v", err)
  129. }
  130. defer file.Close()
  131. // Copy the file to the volume via the temporary container
  132. err = cli.CopyToContainer(ctx, resp.ID, targetPath, file, types.CopyToContainerOptions{})
  133. if err != nil {
  134. return err
  135. }
  136. // remove temporary container
  137. if err := cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{Force: true}); err != nil {
  138. return err
  139. }
  140. return nil
  141. }