auth.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package registry
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "path"
  11. "strings"
  12. "github.com/docker/docker/utils"
  13. )
  14. const (
  15. // Where we store the config file
  16. CONFIGFILE = ".dockercfg"
  17. )
  18. var (
  19. ErrConfigFileMissing = errors.New("The Auth config file is missing")
  20. )
  21. type AuthConfig struct {
  22. Username string `json:"username,omitempty"`
  23. Password string `json:"password,omitempty"`
  24. Auth string `json:"auth"`
  25. Email string `json:"email"`
  26. ServerAddress string `json:"serveraddress,omitempty"`
  27. }
  28. type ConfigFile struct {
  29. Configs map[string]AuthConfig `json:"configs,omitempty"`
  30. rootPath string
  31. }
  32. // create a base64 encoded auth string to store in config
  33. func encodeAuth(authConfig *AuthConfig) string {
  34. authStr := authConfig.Username + ":" + authConfig.Password
  35. msg := []byte(authStr)
  36. encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
  37. base64.StdEncoding.Encode(encoded, msg)
  38. return string(encoded)
  39. }
  40. // decode the auth string
  41. func decodeAuth(authStr string) (string, string, error) {
  42. decLen := base64.StdEncoding.DecodedLen(len(authStr))
  43. decoded := make([]byte, decLen)
  44. authByte := []byte(authStr)
  45. n, err := base64.StdEncoding.Decode(decoded, authByte)
  46. if err != nil {
  47. return "", "", err
  48. }
  49. if n > decLen {
  50. return "", "", fmt.Errorf("Something went wrong decoding auth config")
  51. }
  52. arr := strings.SplitN(string(decoded), ":", 2)
  53. if len(arr) != 2 {
  54. return "", "", fmt.Errorf("Invalid auth configuration file")
  55. }
  56. password := strings.Trim(arr[1], "\x00")
  57. return arr[0], password, nil
  58. }
  59. // load up the auth config information and return values
  60. // FIXME: use the internal golang config parser
  61. func LoadConfig(rootPath string) (*ConfigFile, error) {
  62. configFile := ConfigFile{Configs: make(map[string]AuthConfig), rootPath: rootPath}
  63. confFile := path.Join(rootPath, CONFIGFILE)
  64. if _, err := os.Stat(confFile); err != nil {
  65. return &configFile, nil //missing file is not an error
  66. }
  67. b, err := ioutil.ReadFile(confFile)
  68. if err != nil {
  69. return &configFile, err
  70. }
  71. if err := json.Unmarshal(b, &configFile.Configs); err != nil {
  72. arr := strings.Split(string(b), "\n")
  73. if len(arr) < 2 {
  74. return &configFile, fmt.Errorf("The Auth config file is empty")
  75. }
  76. authConfig := AuthConfig{}
  77. origAuth := strings.Split(arr[0], " = ")
  78. if len(origAuth) != 2 {
  79. return &configFile, fmt.Errorf("Invalid Auth config file")
  80. }
  81. authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
  82. if err != nil {
  83. return &configFile, err
  84. }
  85. origEmail := strings.Split(arr[1], " = ")
  86. if len(origEmail) != 2 {
  87. return &configFile, fmt.Errorf("Invalid Auth config file")
  88. }
  89. authConfig.Email = origEmail[1]
  90. authConfig.ServerAddress = IndexServerAddress()
  91. // *TODO: Switch to using IndexServerName() instead?
  92. configFile.Configs[IndexServerAddress()] = authConfig
  93. } else {
  94. for k, authConfig := range configFile.Configs {
  95. authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth)
  96. if err != nil {
  97. return &configFile, err
  98. }
  99. authConfig.Auth = ""
  100. authConfig.ServerAddress = k
  101. configFile.Configs[k] = authConfig
  102. }
  103. }
  104. return &configFile, nil
  105. }
  106. // save the auth config
  107. func SaveConfig(configFile *ConfigFile) error {
  108. confFile := path.Join(configFile.rootPath, CONFIGFILE)
  109. if len(configFile.Configs) == 0 {
  110. os.Remove(confFile)
  111. return nil
  112. }
  113. configs := make(map[string]AuthConfig, len(configFile.Configs))
  114. for k, authConfig := range configFile.Configs {
  115. authCopy := authConfig
  116. authCopy.Auth = encodeAuth(&authCopy)
  117. authCopy.Username = ""
  118. authCopy.Password = ""
  119. authCopy.ServerAddress = ""
  120. configs[k] = authCopy
  121. }
  122. b, err := json.Marshal(configs)
  123. if err != nil {
  124. return err
  125. }
  126. err = ioutil.WriteFile(confFile, b, 0600)
  127. if err != nil {
  128. return err
  129. }
  130. return nil
  131. }
  132. // try to register/login to the registry server
  133. func Login(authConfig *AuthConfig, factory *utils.HTTPRequestFactory) (string, error) {
  134. var (
  135. status string
  136. reqBody []byte
  137. err error
  138. client = &http.Client{
  139. Transport: &http.Transport{
  140. DisableKeepAlives: true,
  141. Proxy: http.ProxyFromEnvironment,
  142. },
  143. CheckRedirect: AddRequiredHeadersToRedirectedRequests,
  144. }
  145. reqStatusCode = 0
  146. serverAddress = authConfig.ServerAddress
  147. )
  148. if serverAddress == "" {
  149. return "", fmt.Errorf("Server Error: Server Address not set.")
  150. }
  151. loginAgainstOfficialIndex := serverAddress == IndexServerAddress()
  152. // to avoid sending the server address to the server it should be removed before being marshalled
  153. authCopy := *authConfig
  154. authCopy.ServerAddress = ""
  155. jsonBody, err := json.Marshal(authCopy)
  156. if err != nil {
  157. return "", fmt.Errorf("Config Error: %s", err)
  158. }
  159. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
  160. b := strings.NewReader(string(jsonBody))
  161. req1, err := http.Post(serverAddress+"users/", "application/json; charset=utf-8", b)
  162. if err != nil {
  163. return "", fmt.Errorf("Server Error: %s", err)
  164. }
  165. reqStatusCode = req1.StatusCode
  166. defer req1.Body.Close()
  167. reqBody, err = ioutil.ReadAll(req1.Body)
  168. if err != nil {
  169. return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
  170. }
  171. if reqStatusCode == 201 {
  172. if loginAgainstOfficialIndex {
  173. status = "Account created. Please use the confirmation link we sent" +
  174. " to your e-mail to activate it."
  175. } else {
  176. // *TODO: Use registry configuration to determine what this says, if anything?
  177. status = "Account created. Please see the documentation of the registry " + serverAddress + " for instructions how to activate it."
  178. }
  179. } else if reqStatusCode == 400 {
  180. if string(reqBody) == "\"Username or email already exists\"" {
  181. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  182. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  183. resp, err := client.Do(req)
  184. if err != nil {
  185. return "", err
  186. }
  187. defer resp.Body.Close()
  188. body, err := ioutil.ReadAll(resp.Body)
  189. if err != nil {
  190. return "", err
  191. }
  192. if resp.StatusCode == 200 {
  193. return "Login Succeeded", nil
  194. } else if resp.StatusCode == 401 {
  195. return "", fmt.Errorf("Wrong login/password, please try again")
  196. } else if resp.StatusCode == 403 {
  197. if loginAgainstOfficialIndex {
  198. return "", fmt.Errorf("Login: Account is not Active. Please check your e-mail for a confirmation link.")
  199. }
  200. // *TODO: Use registry configuration to determine what this says, if anything?
  201. return "", fmt.Errorf("Login: Account is not Active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)
  202. }
  203. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, resp.StatusCode, resp.Header)
  204. }
  205. return "", fmt.Errorf("Registration: %s", reqBody)
  206. } else if reqStatusCode == 401 {
  207. // This case would happen with private registries where /v1/users is
  208. // protected, so people can use `docker login` as an auth check.
  209. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  210. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  211. resp, err := client.Do(req)
  212. if err != nil {
  213. return "", err
  214. }
  215. defer resp.Body.Close()
  216. body, err := ioutil.ReadAll(resp.Body)
  217. if err != nil {
  218. return "", err
  219. }
  220. if resp.StatusCode == 200 {
  221. return "Login Succeeded", nil
  222. } else if resp.StatusCode == 401 {
  223. return "", fmt.Errorf("Wrong login/password, please try again")
  224. } else {
  225. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  226. resp.StatusCode, resp.Header)
  227. }
  228. } else {
  229. return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
  230. }
  231. return status, nil
  232. }
  233. // this method matches a auth configuration to a server address or a url
  234. func (config *ConfigFile) ResolveAuthConfig(index *IndexInfo) AuthConfig {
  235. configKey := index.GetAuthConfigKey()
  236. // First try the happy case
  237. if c, found := config.Configs[configKey]; found || index.Official {
  238. return c
  239. }
  240. convertToHostname := func(url string) string {
  241. stripped := url
  242. if strings.HasPrefix(url, "http://") {
  243. stripped = strings.Replace(url, "http://", "", 1)
  244. } else if strings.HasPrefix(url, "https://") {
  245. stripped = strings.Replace(url, "https://", "", 1)
  246. }
  247. nameParts := strings.SplitN(stripped, "/", 2)
  248. return nameParts[0]
  249. }
  250. // Maybe they have a legacy config file, we will iterate the keys converting
  251. // them to the new format and testing
  252. for registry, config := range config.Configs {
  253. if configKey == convertToHostname(registry) {
  254. return config
  255. }
  256. }
  257. // When all else fails, return an empty auth config
  258. return AuthConfig{}
  259. }