file.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package configfile
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "github.com/docker/docker/api/types"
  12. )
  13. const (
  14. // This constant is only used for really old config files when the
  15. // URL wasn't saved as part of the config file and it was just
  16. // assumed to be this value.
  17. defaultIndexserver = "https://index.docker.io/v1/"
  18. )
  19. // ConfigFile ~/.docker/config.json file info
  20. type ConfigFile struct {
  21. AuthConfigs map[string]types.AuthConfig `json:"auths"`
  22. HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
  23. PsFormat string `json:"psFormat,omitempty"`
  24. ImagesFormat string `json:"imagesFormat,omitempty"`
  25. NetworksFormat string `json:"networksFormat,omitempty"`
  26. VolumesFormat string `json:"volumesFormat,omitempty"`
  27. StatsFormat string `json:"statsFormat,omitempty"`
  28. DetachKeys string `json:"detachKeys,omitempty"`
  29. CredentialsStore string `json:"credsStore,omitempty"`
  30. CredentialHelpers map[string]string `json:"credHelpers,omitempty"`
  31. Filename string `json:"-"` // Note: for internal use only
  32. ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"`
  33. }
  34. // LegacyLoadFromReader reads the non-nested configuration data given and sets up the
  35. // auth config information with given directory and populates the receiver object
  36. func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error {
  37. b, err := ioutil.ReadAll(configData)
  38. if err != nil {
  39. return err
  40. }
  41. if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil {
  42. arr := strings.Split(string(b), "\n")
  43. if len(arr) < 2 {
  44. return fmt.Errorf("The Auth config file is empty")
  45. }
  46. authConfig := types.AuthConfig{}
  47. origAuth := strings.Split(arr[0], " = ")
  48. if len(origAuth) != 2 {
  49. return fmt.Errorf("Invalid Auth config file")
  50. }
  51. authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
  52. if err != nil {
  53. return err
  54. }
  55. authConfig.ServerAddress = defaultIndexserver
  56. configFile.AuthConfigs[defaultIndexserver] = authConfig
  57. } else {
  58. for k, authConfig := range configFile.AuthConfigs {
  59. authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth)
  60. if err != nil {
  61. return err
  62. }
  63. authConfig.Auth = ""
  64. authConfig.ServerAddress = k
  65. configFile.AuthConfigs[k] = authConfig
  66. }
  67. }
  68. return nil
  69. }
  70. // LoadFromReader reads the configuration data given and sets up the auth config
  71. // information with given directory and populates the receiver object
  72. func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error {
  73. if err := json.NewDecoder(configData).Decode(&configFile); err != nil {
  74. return err
  75. }
  76. var err error
  77. for addr, ac := range configFile.AuthConfigs {
  78. ac.Username, ac.Password, err = decodeAuth(ac.Auth)
  79. if err != nil {
  80. return err
  81. }
  82. ac.Auth = ""
  83. ac.ServerAddress = addr
  84. configFile.AuthConfigs[addr] = ac
  85. }
  86. return nil
  87. }
  88. // ContainsAuth returns whether there is authentication configured
  89. // in this file or not.
  90. func (configFile *ConfigFile) ContainsAuth() bool {
  91. return configFile.CredentialsStore != "" ||
  92. len(configFile.CredentialHelpers) > 0 ||
  93. len(configFile.AuthConfigs) > 0
  94. }
  95. // SaveToWriter encodes and writes out all the authorization information to
  96. // the given writer
  97. func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error {
  98. // Encode sensitive data into a new/temp struct
  99. tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs))
  100. for k, authConfig := range configFile.AuthConfigs {
  101. authCopy := authConfig
  102. // encode and save the authstring, while blanking out the original fields
  103. authCopy.Auth = encodeAuth(&authCopy)
  104. authCopy.Username = ""
  105. authCopy.Password = ""
  106. authCopy.ServerAddress = ""
  107. tmpAuthConfigs[k] = authCopy
  108. }
  109. saveAuthConfigs := configFile.AuthConfigs
  110. configFile.AuthConfigs = tmpAuthConfigs
  111. defer func() { configFile.AuthConfigs = saveAuthConfigs }()
  112. data, err := json.MarshalIndent(configFile, "", "\t")
  113. if err != nil {
  114. return err
  115. }
  116. _, err = writer.Write(data)
  117. return err
  118. }
  119. // Save encodes and writes out all the authorization information
  120. func (configFile *ConfigFile) Save() error {
  121. if configFile.Filename == "" {
  122. return fmt.Errorf("Can't save config with empty filename")
  123. }
  124. if err := os.MkdirAll(filepath.Dir(configFile.Filename), 0700); err != nil {
  125. return err
  126. }
  127. f, err := os.OpenFile(configFile.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  128. if err != nil {
  129. return err
  130. }
  131. defer f.Close()
  132. return configFile.SaveToWriter(f)
  133. }
  134. // encodeAuth creates a base64 encoded string to containing authorization information
  135. func encodeAuth(authConfig *types.AuthConfig) string {
  136. if authConfig.Username == "" && authConfig.Password == "" {
  137. return ""
  138. }
  139. authStr := authConfig.Username + ":" + authConfig.Password
  140. msg := []byte(authStr)
  141. encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
  142. base64.StdEncoding.Encode(encoded, msg)
  143. return string(encoded)
  144. }
  145. // decodeAuth decodes a base64 encoded string and returns username and password
  146. func decodeAuth(authStr string) (string, string, error) {
  147. if authStr == "" {
  148. return "", "", nil
  149. }
  150. decLen := base64.StdEncoding.DecodedLen(len(authStr))
  151. decoded := make([]byte, decLen)
  152. authByte := []byte(authStr)
  153. n, err := base64.StdEncoding.Decode(decoded, authByte)
  154. if err != nil {
  155. return "", "", err
  156. }
  157. if n > decLen {
  158. return "", "", fmt.Errorf("Something went wrong decoding auth config")
  159. }
  160. arr := strings.SplitN(string(decoded), ":", 2)
  161. if len(arr) != 2 {
  162. return "", "", fmt.Errorf("Invalid auth configuration file")
  163. }
  164. password := strings.Trim(arr[1], "\x00")
  165. return arr[0], password, nil
  166. }