docker_container_windows.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // +build windows
  2. /*
  3. Copyright 2019 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package dockershim
  15. import (
  16. "crypto/rand"
  17. "encoding/hex"
  18. "fmt"
  19. "regexp"
  20. "golang.org/x/sys/windows/registry"
  21. dockertypes "github.com/docker/docker/api/types"
  22. dockercontainer "github.com/docker/docker/api/types/container"
  23. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  24. )
  25. type containerCleanupInfo struct {
  26. gMSARegistryValueName string
  27. }
  28. // applyPlatformSpecificDockerConfig applies platform-specific configurations to a dockertypes.ContainerCreateConfig struct.
  29. // The containerCleanupInfo struct it returns will be passed as is to performPlatformSpecificContainerCleanup
  30. // after either the container creation has failed or the container has been removed.
  31. func (ds *dockerService) applyPlatformSpecificDockerConfig(request *runtimeapi.CreateContainerRequest, createConfig *dockertypes.ContainerCreateConfig) (*containerCleanupInfo, error) {
  32. cleanupInfo := &containerCleanupInfo{}
  33. if err := applyGMSAConfig(request.GetConfig(), createConfig, cleanupInfo); err != nil {
  34. return nil, err
  35. }
  36. return cleanupInfo, nil
  37. }
  38. // applyGMSAConfig looks at the container's .Windows.SecurityContext.GMSACredentialSpec field; if present,
  39. // it copies its contents to a unique registry value, and sets a SecurityOpt on the config pointing to that registry value.
  40. // We use registry values instead of files since their location cannot change - as opposed to credential spec files,
  41. // whose location could potentially change down the line, or even be unknown (eg if docker is not installed on the
  42. // C: drive)
  43. // When docker supports passing a credential spec's contents directly, we should switch to using that
  44. // as it will avoid cluttering the registry - there is a moby PR out for this:
  45. // https://github.com/moby/moby/pull/38777
  46. func applyGMSAConfig(config *runtimeapi.ContainerConfig, createConfig *dockertypes.ContainerCreateConfig, cleanupInfo *containerCleanupInfo) error {
  47. var credSpec string
  48. if config.Windows != nil && config.Windows.SecurityContext != nil {
  49. credSpec = config.Windows.SecurityContext.CredentialSpec
  50. }
  51. if credSpec == "" {
  52. return nil
  53. }
  54. valueName, err := copyGMSACredSpecToRegistryValue(credSpec)
  55. if err != nil {
  56. return err
  57. }
  58. if createConfig.HostConfig == nil {
  59. createConfig.HostConfig = &dockercontainer.HostConfig{}
  60. }
  61. createConfig.HostConfig.SecurityOpt = append(createConfig.HostConfig.SecurityOpt, "credentialspec=registry://"+valueName)
  62. cleanupInfo.gMSARegistryValueName = valueName
  63. return nil
  64. }
  65. const (
  66. // same as https://github.com/moby/moby/blob/93d994e29c9cc8d81f1b0477e28d705fa7e2cd72/daemon/oci_windows.go#L23
  67. credentialSpecRegistryLocation = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs`
  68. // the prefix for the registry values we write GMSA cred specs to
  69. gMSARegistryValueNamePrefix = "k8s-cred-spec-"
  70. // the number of random bytes to generate suffixes for registry value names
  71. gMSARegistryValueNameSuffixRandomBytes = 40
  72. )
  73. // registryKey is an interface wrapper around `registry.Key`,
  74. // listing only the methods we care about here.
  75. // It's mainly useful to easily allow mocking the registry in tests.
  76. type registryKey interface {
  77. SetStringValue(name, value string) error
  78. DeleteValue(name string) error
  79. ReadValueNames(n int) ([]string, error)
  80. Close() error
  81. }
  82. var registryCreateKeyFunc = func(baseKey registry.Key, path string, access uint32) (registryKey, bool, error) {
  83. return registry.CreateKey(baseKey, path, access)
  84. }
  85. // randomReader is only meant to ever be overridden for testing purposes,
  86. // same idea as for `registryKey` above
  87. var randomReader = rand.Reader
  88. // gMSARegistryValueNamesRegex is the regex used to detect gMSA cred spec
  89. // registry values in `removeAllGMSARegistryValues` below.
  90. var gMSARegistryValueNamesRegex = regexp.MustCompile(fmt.Sprintf("^%s[0-9a-f]{%d}$", gMSARegistryValueNamePrefix, 2*gMSARegistryValueNameSuffixRandomBytes))
  91. // copyGMSACredSpecToRegistryKey copies the credential specs to a unique registry value, and returns its name.
  92. func copyGMSACredSpecToRegistryValue(credSpec string) (string, error) {
  93. valueName, err := gMSARegistryValueName()
  94. if err != nil {
  95. return "", err
  96. }
  97. // write to the registry
  98. key, _, err := registryCreateKeyFunc(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.SET_VALUE)
  99. if err != nil {
  100. return "", fmt.Errorf("unable to open registry key %q: %v", credentialSpecRegistryLocation, err)
  101. }
  102. defer key.Close()
  103. if err = key.SetStringValue(valueName, credSpec); err != nil {
  104. return "", fmt.Errorf("unable to write into registry value %q/%q: %v", credentialSpecRegistryLocation, valueName, err)
  105. }
  106. return valueName, nil
  107. }
  108. // gMSARegistryValueName computes the name of the registry value where to store the GMSA cred spec contents.
  109. // The value's name is a purely random suffix appended to `gMSARegistryValueNamePrefix`.
  110. func gMSARegistryValueName() (string, error) {
  111. randomSuffix, err := randomString(gMSARegistryValueNameSuffixRandomBytes)
  112. if err != nil {
  113. return "", fmt.Errorf("error when generating gMSA registry value name: %v", err)
  114. }
  115. return gMSARegistryValueNamePrefix + randomSuffix, nil
  116. }
  117. // randomString returns a random hex string.
  118. func randomString(length int) (string, error) {
  119. randBytes := make([]byte, length)
  120. if n, err := randomReader.Read(randBytes); err != nil || n != length {
  121. if err == nil {
  122. err = fmt.Errorf("only got %v random bytes, expected %v", n, length)
  123. }
  124. return "", fmt.Errorf("unable to generate random string: %v", err)
  125. }
  126. return hex.EncodeToString(randBytes), nil
  127. }
  128. // performPlatformSpecificContainerCleanup is responsible for doing any platform-specific cleanup
  129. // after either the container creation has failed or the container has been removed.
  130. func (ds *dockerService) performPlatformSpecificContainerCleanup(cleanupInfo *containerCleanupInfo) (errors []error) {
  131. if err := removeGMSARegistryValue(cleanupInfo); err != nil {
  132. errors = append(errors, err)
  133. }
  134. return
  135. }
  136. func removeGMSARegistryValue(cleanupInfo *containerCleanupInfo) error {
  137. if cleanupInfo == nil || cleanupInfo.gMSARegistryValueName == "" {
  138. return nil
  139. }
  140. key, _, err := registryCreateKeyFunc(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.SET_VALUE)
  141. if err != nil {
  142. return fmt.Errorf("unable to open registry key %q: %v", credentialSpecRegistryLocation, err)
  143. }
  144. defer key.Close()
  145. if err = key.DeleteValue(cleanupInfo.gMSARegistryValueName); err != nil {
  146. return fmt.Errorf("unable to remove registry value %q/%q: %v", credentialSpecRegistryLocation, cleanupInfo.gMSARegistryValueName, err)
  147. }
  148. return nil
  149. }
  150. // platformSpecificContainerInitCleanup is called when dockershim
  151. // is starting, and is meant to clean up any cruft left by previous runs
  152. // creating containers.
  153. // Errors are simply logged, but don't prevent dockershim from starting.
  154. func (ds *dockerService) platformSpecificContainerInitCleanup() (errors []error) {
  155. return removeAllGMSARegistryValues()
  156. }
  157. func removeAllGMSARegistryValues() (errors []error) {
  158. key, _, err := registryCreateKeyFunc(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.SET_VALUE)
  159. if err != nil {
  160. return []error{fmt.Errorf("unable to open registry key %q: %v", credentialSpecRegistryLocation, err)}
  161. }
  162. defer key.Close()
  163. valueNames, err := key.ReadValueNames(0)
  164. if err != nil {
  165. return []error{fmt.Errorf("unable to list values under registry key %q: %v", credentialSpecRegistryLocation, err)}
  166. }
  167. for _, valueName := range valueNames {
  168. if gMSARegistryValueNamesRegex.MatchString(valueName) {
  169. if err = key.DeleteValue(valueName); err != nil {
  170. errors = append(errors, fmt.Errorf("unable to remove registry value %q/%q: %v", credentialSpecRegistryLocation, valueName, err))
  171. }
  172. }
  173. }
  174. return
  175. }