sandbox_externalkey_unix.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. //go:build linux || freebsd
  2. // +build linux freebsd
  3. package libnetwork
  4. import (
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "net"
  10. "os"
  11. "path/filepath"
  12. "github.com/docker/docker/libnetwork/types"
  13. "github.com/docker/docker/pkg/stringid"
  14. "github.com/opencontainers/runtime-spec/specs-go"
  15. "github.com/sirupsen/logrus"
  16. )
  17. const (
  18. execSubdir = "libnetwork"
  19. defaultExecRoot = "/run/docker"
  20. success = "success"
  21. )
  22. // processSetKeyReexec is a private function that must be called only on an reexec path
  23. // It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <short-controller-id> }
  24. // It also expects specs.State as a json string in <stdin>
  25. // Refer to https://github.com/opencontainers/runc/pull/160/ for more information
  26. // The docker exec-root can be specified as "-exec-root" flag. The default value is "/run/docker".
  27. func processSetKeyReexec() {
  28. if err := setKey(); err != nil {
  29. _, _ = fmt.Fprintln(os.Stderr, err)
  30. os.Exit(1)
  31. }
  32. }
  33. func setKey() error {
  34. execRoot := flag.String("exec-root", defaultExecRoot, "docker exec root")
  35. flag.Parse()
  36. // expecting 3 os.Args {[0]="libnetwork-setkey", [1]=<container-id>, [2]=<short-controller-id> }
  37. // (i.e. expecting 2 flag.Args())
  38. args := flag.Args()
  39. if len(args) < 2 {
  40. return fmt.Errorf("re-exec expects 2 args (after parsing flags), received : %d", len(args))
  41. }
  42. containerID, shortCtlrID := args[0], args[1]
  43. // We expect specs.State as a json string in <stdin>
  44. stateBuf, err := io.ReadAll(os.Stdin)
  45. if err != nil {
  46. return err
  47. }
  48. var state specs.State
  49. if err = json.Unmarshal(stateBuf, &state); err != nil {
  50. return err
  51. }
  52. return SetExternalKey(shortCtlrID, containerID, fmt.Sprintf("/proc/%d/ns/net", state.Pid), *execRoot)
  53. }
  54. // SetExternalKey provides a convenient way to set an External key to a sandbox
  55. func SetExternalKey(shortCtlrID string, containerID string, key string, execRoot string) error {
  56. keyData := setKeyData{
  57. ContainerID: containerID,
  58. Key: key}
  59. uds := filepath.Join(execRoot, execSubdir, shortCtlrID+".sock")
  60. c, err := net.Dial("unix", uds)
  61. if err != nil {
  62. return err
  63. }
  64. defer c.Close()
  65. if err = sendKey(c, keyData); err != nil {
  66. return fmt.Errorf("sendKey failed with : %v", err)
  67. }
  68. return processReturn(c)
  69. }
  70. func sendKey(c net.Conn, data setKeyData) error {
  71. var err error
  72. defer func() {
  73. if err != nil {
  74. c.Close()
  75. }
  76. }()
  77. var b []byte
  78. if b, err = json.Marshal(data); err != nil {
  79. return err
  80. }
  81. _, err = c.Write(b)
  82. return err
  83. }
  84. func processReturn(r io.Reader) error {
  85. buf := make([]byte, 1024)
  86. n, err := r.Read(buf[:])
  87. if err != nil {
  88. return fmt.Errorf("failed to read buf in processReturn : %v", err)
  89. }
  90. if string(buf[0:n]) != success {
  91. return fmt.Errorf(string(buf[0:n]))
  92. }
  93. return nil
  94. }
  95. func (c *Controller) startExternalKeyListener() error {
  96. execRoot := defaultExecRoot
  97. if v := c.Config().ExecRoot; v != "" {
  98. execRoot = v
  99. }
  100. udsBase := filepath.Join(execRoot, execSubdir)
  101. if err := os.MkdirAll(udsBase, 0600); err != nil {
  102. return err
  103. }
  104. shortCtlrID := stringid.TruncateID(c.id)
  105. uds := filepath.Join(udsBase, shortCtlrID+".sock")
  106. l, err := net.Listen("unix", uds)
  107. if err != nil {
  108. return err
  109. }
  110. if err := os.Chmod(uds, 0600); err != nil {
  111. l.Close()
  112. return err
  113. }
  114. c.mu.Lock()
  115. c.extKeyListener = l
  116. c.mu.Unlock()
  117. go c.acceptClientConnections(uds, l)
  118. return nil
  119. }
  120. func (c *Controller) acceptClientConnections(sock string, l net.Listener) {
  121. for {
  122. conn, err := l.Accept()
  123. if err != nil {
  124. if _, err1 := os.Stat(sock); os.IsNotExist(err1) {
  125. logrus.Debugf("Unix socket %s doesn't exist. cannot accept client connections", sock)
  126. return
  127. }
  128. logrus.Errorf("Error accepting connection %v", err)
  129. continue
  130. }
  131. go func() {
  132. defer conn.Close()
  133. err := c.processExternalKey(conn)
  134. ret := success
  135. if err != nil {
  136. ret = err.Error()
  137. }
  138. _, err = conn.Write([]byte(ret))
  139. if err != nil {
  140. logrus.Errorf("Error returning to the client %v", err)
  141. }
  142. }()
  143. }
  144. }
  145. func (c *Controller) processExternalKey(conn net.Conn) error {
  146. buf := make([]byte, 1280)
  147. nr, err := conn.Read(buf)
  148. if err != nil {
  149. return err
  150. }
  151. var s setKeyData
  152. if err = json.Unmarshal(buf[0:nr], &s); err != nil {
  153. return err
  154. }
  155. var sandbox *Sandbox
  156. search := SandboxContainerWalker(&sandbox, s.ContainerID)
  157. c.WalkSandboxes(search)
  158. if sandbox == nil {
  159. return types.BadRequestErrorf("no sandbox present for %s", s.ContainerID)
  160. }
  161. return sandbox.SetKey(s.Key)
  162. }
  163. func (c *Controller) stopExternalKeyListener() {
  164. c.extKeyListener.Close()
  165. }