auth.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. "sync"
  13. "time"
  14. log "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/utils"
  16. )
  17. const (
  18. // Where we store the config file
  19. CONFIGFILE = ".dockercfg"
  20. )
  21. var (
  22. ErrConfigFileMissing = errors.New("The Auth config file is missing")
  23. )
  24. type AuthConfig struct {
  25. Username string `json:"username,omitempty"`
  26. Password string `json:"password,omitempty"`
  27. Auth string `json:"auth"`
  28. Email string `json:"email"`
  29. ServerAddress string `json:"serveraddress,omitempty"`
  30. }
  31. type ConfigFile struct {
  32. Configs map[string]AuthConfig `json:"configs,omitempty"`
  33. rootPath string
  34. }
  35. type RequestAuthorization struct {
  36. authConfig *AuthConfig
  37. registryEndpoint *Endpoint
  38. resource string
  39. scope string
  40. actions []string
  41. tokenLock sync.Mutex
  42. tokenCache string
  43. tokenExpiration time.Time
  44. }
  45. func NewRequestAuthorization(authConfig *AuthConfig, registryEndpoint *Endpoint, resource, scope string, actions []string) *RequestAuthorization {
  46. return &RequestAuthorization{
  47. authConfig: authConfig,
  48. registryEndpoint: registryEndpoint,
  49. resource: resource,
  50. scope: scope,
  51. actions: actions,
  52. }
  53. }
  54. func (auth *RequestAuthorization) getToken() (string, error) {
  55. auth.tokenLock.Lock()
  56. defer auth.tokenLock.Unlock()
  57. now := time.Now()
  58. if now.Before(auth.tokenExpiration) {
  59. log.Debugf("Using cached token for %s", auth.authConfig.Username)
  60. return auth.tokenCache, nil
  61. }
  62. client := &http.Client{
  63. Transport: &http.Transport{
  64. DisableKeepAlives: true,
  65. Proxy: http.ProxyFromEnvironment},
  66. CheckRedirect: AddRequiredHeadersToRedirectedRequests,
  67. }
  68. factory := HTTPRequestFactory(nil)
  69. for _, challenge := range auth.registryEndpoint.AuthChallenges {
  70. switch strings.ToLower(challenge.Scheme) {
  71. case "basic":
  72. // no token necessary
  73. case "bearer":
  74. log.Debugf("Getting bearer token with %s for %s", challenge.Parameters, auth.authConfig.Username)
  75. params := map[string]string{}
  76. for k, v := range challenge.Parameters {
  77. params[k] = v
  78. }
  79. params["scope"] = fmt.Sprintf("%s:%s:%s", auth.resource, auth.scope, strings.Join(auth.actions, ","))
  80. token, err := getToken(auth.authConfig.Username, auth.authConfig.Password, params, auth.registryEndpoint, client, factory)
  81. if err != nil {
  82. return "", err
  83. }
  84. auth.tokenCache = token
  85. auth.tokenExpiration = now.Add(time.Minute)
  86. return token, nil
  87. default:
  88. log.Infof("Unsupported auth scheme: %q", challenge.Scheme)
  89. }
  90. }
  91. // Do not expire cache since there are no challenges which use a token
  92. auth.tokenExpiration = time.Now().Add(time.Hour * 24)
  93. return "", nil
  94. }
  95. func (auth *RequestAuthorization) Authorize(req *http.Request) error {
  96. token, err := auth.getToken()
  97. if err != nil {
  98. return err
  99. }
  100. if token != "" {
  101. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
  102. } else if auth.authConfig.Username != "" && auth.authConfig.Password != "" {
  103. req.SetBasicAuth(auth.authConfig.Username, auth.authConfig.Password)
  104. }
  105. return nil
  106. }
  107. // create a base64 encoded auth string to store in config
  108. func encodeAuth(authConfig *AuthConfig) string {
  109. authStr := authConfig.Username + ":" + authConfig.Password
  110. msg := []byte(authStr)
  111. encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
  112. base64.StdEncoding.Encode(encoded, msg)
  113. return string(encoded)
  114. }
  115. // decode the auth string
  116. func decodeAuth(authStr string) (string, string, error) {
  117. decLen := base64.StdEncoding.DecodedLen(len(authStr))
  118. decoded := make([]byte, decLen)
  119. authByte := []byte(authStr)
  120. n, err := base64.StdEncoding.Decode(decoded, authByte)
  121. if err != nil {
  122. return "", "", err
  123. }
  124. if n > decLen {
  125. return "", "", fmt.Errorf("Something went wrong decoding auth config")
  126. }
  127. arr := strings.SplitN(string(decoded), ":", 2)
  128. if len(arr) != 2 {
  129. return "", "", fmt.Errorf("Invalid auth configuration file")
  130. }
  131. password := strings.Trim(arr[1], "\x00")
  132. return arr[0], password, nil
  133. }
  134. // load up the auth config information and return values
  135. // FIXME: use the internal golang config parser
  136. func LoadConfig(rootPath string) (*ConfigFile, error) {
  137. configFile := ConfigFile{Configs: make(map[string]AuthConfig), rootPath: rootPath}
  138. confFile := path.Join(rootPath, CONFIGFILE)
  139. if _, err := os.Stat(confFile); err != nil {
  140. return &configFile, nil //missing file is not an error
  141. }
  142. b, err := ioutil.ReadFile(confFile)
  143. if err != nil {
  144. return &configFile, err
  145. }
  146. if err := json.Unmarshal(b, &configFile.Configs); err != nil {
  147. arr := strings.Split(string(b), "\n")
  148. if len(arr) < 2 {
  149. return &configFile, fmt.Errorf("The Auth config file is empty")
  150. }
  151. authConfig := AuthConfig{}
  152. origAuth := strings.Split(arr[0], " = ")
  153. if len(origAuth) != 2 {
  154. return &configFile, fmt.Errorf("Invalid Auth config file")
  155. }
  156. authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
  157. if err != nil {
  158. return &configFile, err
  159. }
  160. origEmail := strings.Split(arr[1], " = ")
  161. if len(origEmail) != 2 {
  162. return &configFile, fmt.Errorf("Invalid Auth config file")
  163. }
  164. authConfig.Email = origEmail[1]
  165. authConfig.ServerAddress = IndexServerAddress()
  166. // *TODO: Switch to using IndexServerName() instead?
  167. configFile.Configs[IndexServerAddress()] = authConfig
  168. } else {
  169. for k, authConfig := range configFile.Configs {
  170. authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth)
  171. if err != nil {
  172. return &configFile, err
  173. }
  174. authConfig.Auth = ""
  175. authConfig.ServerAddress = k
  176. configFile.Configs[k] = authConfig
  177. }
  178. }
  179. return &configFile, nil
  180. }
  181. // save the auth config
  182. func SaveConfig(configFile *ConfigFile) error {
  183. confFile := path.Join(configFile.rootPath, CONFIGFILE)
  184. if len(configFile.Configs) == 0 {
  185. os.Remove(confFile)
  186. return nil
  187. }
  188. configs := make(map[string]AuthConfig, len(configFile.Configs))
  189. for k, authConfig := range configFile.Configs {
  190. authCopy := authConfig
  191. authCopy.Auth = encodeAuth(&authCopy)
  192. authCopy.Username = ""
  193. authCopy.Password = ""
  194. authCopy.ServerAddress = ""
  195. configs[k] = authCopy
  196. }
  197. b, err := json.MarshalIndent(configs, "", "\t")
  198. if err != nil {
  199. return err
  200. }
  201. err = ioutil.WriteFile(confFile, b, 0600)
  202. if err != nil {
  203. return err
  204. }
  205. return nil
  206. }
  207. // Login tries to register/login to the registry server.
  208. func Login(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HTTPRequestFactory) (string, error) {
  209. // Separates the v2 registry login logic from the v1 logic.
  210. if registryEndpoint.Version == APIVersion2 {
  211. return loginV2(authConfig, registryEndpoint, factory)
  212. }
  213. return loginV1(authConfig, registryEndpoint, factory)
  214. }
  215. // loginV1 tries to register/login to the v1 registry server.
  216. func loginV1(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HTTPRequestFactory) (string, error) {
  217. var (
  218. status string
  219. reqBody []byte
  220. err error
  221. client = &http.Client{
  222. Transport: &http.Transport{
  223. DisableKeepAlives: true,
  224. Proxy: http.ProxyFromEnvironment,
  225. },
  226. CheckRedirect: AddRequiredHeadersToRedirectedRequests,
  227. }
  228. reqStatusCode = 0
  229. serverAddress = authConfig.ServerAddress
  230. )
  231. log.Debugf("attempting v1 login to registry endpoint %s", registryEndpoint)
  232. if serverAddress == "" {
  233. return "", fmt.Errorf("Server Error: Server Address not set.")
  234. }
  235. loginAgainstOfficialIndex := serverAddress == IndexServerAddress()
  236. // to avoid sending the server address to the server it should be removed before being marshalled
  237. authCopy := *authConfig
  238. authCopy.ServerAddress = ""
  239. jsonBody, err := json.Marshal(authCopy)
  240. if err != nil {
  241. return "", fmt.Errorf("Config Error: %s", err)
  242. }
  243. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
  244. b := strings.NewReader(string(jsonBody))
  245. req1, err := http.Post(serverAddress+"users/", "application/json; charset=utf-8", b)
  246. if err != nil {
  247. return "", fmt.Errorf("Server Error: %s", err)
  248. }
  249. reqStatusCode = req1.StatusCode
  250. defer req1.Body.Close()
  251. reqBody, err = ioutil.ReadAll(req1.Body)
  252. if err != nil {
  253. return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
  254. }
  255. if reqStatusCode == 201 {
  256. if loginAgainstOfficialIndex {
  257. status = "Account created. Please use the confirmation link we sent" +
  258. " to your e-mail to activate it."
  259. } else {
  260. // *TODO: Use registry configuration to determine what this says, if anything?
  261. status = "Account created. Please see the documentation of the registry " + serverAddress + " for instructions how to activate it."
  262. }
  263. } else if reqStatusCode == 400 {
  264. if string(reqBody) == "\"Username or email already exists\"" {
  265. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  266. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  267. resp, err := client.Do(req)
  268. if err != nil {
  269. return "", err
  270. }
  271. defer resp.Body.Close()
  272. body, err := ioutil.ReadAll(resp.Body)
  273. if err != nil {
  274. return "", err
  275. }
  276. if resp.StatusCode == 200 {
  277. return "Login Succeeded", nil
  278. } else if resp.StatusCode == 401 {
  279. return "", fmt.Errorf("Wrong login/password, please try again")
  280. } else if resp.StatusCode == 403 {
  281. if loginAgainstOfficialIndex {
  282. return "", fmt.Errorf("Login: Account is not Active. Please check your e-mail for a confirmation link.")
  283. }
  284. // *TODO: Use registry configuration to determine what this says, if anything?
  285. return "", fmt.Errorf("Login: Account is not Active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)
  286. }
  287. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, resp.StatusCode, resp.Header)
  288. }
  289. return "", fmt.Errorf("Registration: %s", reqBody)
  290. } else if reqStatusCode == 401 {
  291. // This case would happen with private registries where /v1/users is
  292. // protected, so people can use `docker login` as an auth check.
  293. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  294. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  295. resp, err := client.Do(req)
  296. if err != nil {
  297. return "", err
  298. }
  299. defer resp.Body.Close()
  300. body, err := ioutil.ReadAll(resp.Body)
  301. if err != nil {
  302. return "", err
  303. }
  304. if resp.StatusCode == 200 {
  305. return "Login Succeeded", nil
  306. } else if resp.StatusCode == 401 {
  307. return "", fmt.Errorf("Wrong login/password, please try again")
  308. } else {
  309. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  310. resp.StatusCode, resp.Header)
  311. }
  312. } else {
  313. return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
  314. }
  315. return status, nil
  316. }
  317. // loginV2 tries to login to the v2 registry server. The given registry endpoint has been
  318. // pinged or setup with a list of authorization challenges. Each of these challenges are
  319. // tried until one of them succeeds. Currently supported challenge schemes are:
  320. // HTTP Basic Authorization
  321. // Token Authorization with a separate token issuing server
  322. // NOTE: the v2 logic does not attempt to create a user account if one doesn't exist. For
  323. // now, users should create their account through other means like directly from a web page
  324. // served by the v2 registry service provider. Whether this will be supported in the future
  325. // is to be determined.
  326. func loginV2(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HTTPRequestFactory) (string, error) {
  327. log.Debugf("attempting v2 login to registry endpoint %s", registryEndpoint)
  328. client := &http.Client{
  329. Transport: &http.Transport{
  330. DisableKeepAlives: true,
  331. Proxy: http.ProxyFromEnvironment,
  332. },
  333. CheckRedirect: AddRequiredHeadersToRedirectedRequests,
  334. }
  335. var (
  336. err error
  337. allErrors []error
  338. )
  339. for _, challenge := range registryEndpoint.AuthChallenges {
  340. log.Debugf("trying %q auth challenge with params %s", challenge.Scheme, challenge.Parameters)
  341. switch strings.ToLower(challenge.Scheme) {
  342. case "basic":
  343. err = tryV2BasicAuthLogin(authConfig, challenge.Parameters, registryEndpoint, client, factory)
  344. case "bearer":
  345. err = tryV2TokenAuthLogin(authConfig, challenge.Parameters, registryEndpoint, client, factory)
  346. default:
  347. // Unsupported challenge types are explicitly skipped.
  348. err = fmt.Errorf("unsupported auth scheme: %q", challenge.Scheme)
  349. }
  350. if err == nil {
  351. return "Login Succeeded", nil
  352. }
  353. log.Debugf("error trying auth challenge %q: %s", challenge.Scheme, err)
  354. allErrors = append(allErrors, err)
  355. }
  356. return "", fmt.Errorf("no successful auth challenge for %s - errors: %s", registryEndpoint, allErrors)
  357. }
  358. func tryV2BasicAuthLogin(authConfig *AuthConfig, params map[string]string, registryEndpoint *Endpoint, client *http.Client, factory *utils.HTTPRequestFactory) error {
  359. req, err := factory.NewRequest("GET", registryEndpoint.Path(""), nil)
  360. if err != nil {
  361. return err
  362. }
  363. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  364. resp, err := client.Do(req)
  365. if err != nil {
  366. return err
  367. }
  368. defer resp.Body.Close()
  369. if resp.StatusCode != http.StatusOK {
  370. return fmt.Errorf("basic auth attempt to %s realm %q failed with status: %d %s", registryEndpoint, params["realm"], resp.StatusCode, http.StatusText(resp.StatusCode))
  371. }
  372. return nil
  373. }
  374. func tryV2TokenAuthLogin(authConfig *AuthConfig, params map[string]string, registryEndpoint *Endpoint, client *http.Client, factory *utils.HTTPRequestFactory) error {
  375. token, err := getToken(authConfig.Username, authConfig.Password, params, registryEndpoint, client, factory)
  376. if err != nil {
  377. return err
  378. }
  379. req, err := factory.NewRequest("GET", registryEndpoint.Path(""), nil)
  380. if err != nil {
  381. return err
  382. }
  383. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
  384. resp, err := client.Do(req)
  385. if err != nil {
  386. return err
  387. }
  388. defer resp.Body.Close()
  389. if resp.StatusCode != http.StatusOK {
  390. return fmt.Errorf("token auth attempt to %s realm %q failed with status: %d %s", registryEndpoint, params["realm"], resp.StatusCode, http.StatusText(resp.StatusCode))
  391. }
  392. return nil
  393. }
  394. // this method matches a auth configuration to a server address or a url
  395. func (config *ConfigFile) ResolveAuthConfig(index *IndexInfo) AuthConfig {
  396. configKey := index.GetAuthConfigKey()
  397. // First try the happy case
  398. if c, found := config.Configs[configKey]; found || index.Official {
  399. return c
  400. }
  401. convertToHostname := func(url string) string {
  402. stripped := url
  403. if strings.HasPrefix(url, "http://") {
  404. stripped = strings.Replace(url, "http://", "", 1)
  405. } else if strings.HasPrefix(url, "https://") {
  406. stripped = strings.Replace(url, "https://", "", 1)
  407. }
  408. nameParts := strings.SplitN(stripped, "/", 2)
  409. return nameParts[0]
  410. }
  411. // Maybe they have a legacy config file, we will iterate the keys converting
  412. // them to the new format and testing
  413. for registry, config := range config.Configs {
  414. if configKey == convertToHostname(registry) {
  415. return config
  416. }
  417. }
  418. // When all else fails, return an empty auth config
  419. return AuthConfig{}
  420. }