azure_acr_helper.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. Copyright 2017 Microsoft Corporation
  15. MIT License
  16. Copyright (c) Microsoft Corporation. All rights reserved.
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23. The above copyright notice and this permission notice shall be included in all
  24. copies or substantial portions of the Software.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  31. SOFTWARE
  32. */
  33. // Source: https://github.com/Azure/acr-docker-credential-helper/blob/a79b541f3ee761f6cc4511863ed41fb038c19464/src/docker-credential-acr/acr_login.go
  34. package azure
  35. import (
  36. "bytes"
  37. "encoding/json"
  38. "errors"
  39. "fmt"
  40. "io"
  41. "io/ioutil"
  42. "net/http"
  43. "net/url"
  44. "strconv"
  45. "strings"
  46. "unicode"
  47. )
  48. type authDirective struct {
  49. service string
  50. realm string
  51. }
  52. type acrAuthResponse struct {
  53. RefreshToken string `json:"refresh_token"`
  54. }
  55. // 5 minutes buffer time to allow timeshift between local machine and AAD
  56. const timeShiftBuffer = 300
  57. const userAgentHeader = "User-Agent"
  58. const userAgent = "kubernetes-credentialprovider-acr"
  59. const dockerTokenLoginUsernameGUID = "00000000-0000-0000-0000-000000000000"
  60. var client = &http.Client{}
  61. func receiveChallengeFromLoginServer(serverAddress string) (*authDirective, error) {
  62. challengeURL := url.URL{
  63. Scheme: "https",
  64. Host: serverAddress,
  65. Path: "v2/",
  66. }
  67. var err error
  68. var r *http.Request
  69. r, _ = http.NewRequest("GET", challengeURL.String(), nil)
  70. r.Header.Add(userAgentHeader, userAgent)
  71. var challenge *http.Response
  72. if challenge, err = client.Do(r); err != nil {
  73. return nil, fmt.Errorf("Error reaching registry endpoint %s, error: %s", challengeURL.String(), err)
  74. }
  75. defer challenge.Body.Close()
  76. if challenge.StatusCode != 401 {
  77. return nil, fmt.Errorf("Registry did not issue a valid AAD challenge, status: %d", challenge.StatusCode)
  78. }
  79. var authHeader []string
  80. var ok bool
  81. if authHeader, ok = challenge.Header["Www-Authenticate"]; !ok {
  82. return nil, fmt.Errorf("Challenge response does not contain header 'Www-Authenticate'")
  83. }
  84. if len(authHeader) != 1 {
  85. return nil, fmt.Errorf("Registry did not issue a valid AAD challenge, authenticate header [%s]",
  86. strings.Join(authHeader, ", "))
  87. }
  88. authSections := strings.SplitN(authHeader[0], " ", 2)
  89. authType := strings.ToLower(authSections[0])
  90. var authParams *map[string]string
  91. if authParams, err = parseAssignments(authSections[1]); err != nil {
  92. return nil, fmt.Errorf("Unable to understand the contents of Www-Authenticate header %s", authSections[1])
  93. }
  94. // verify headers
  95. if !strings.EqualFold("Bearer", authType) {
  96. return nil, fmt.Errorf("Www-Authenticate: expected realm: Bearer, actual: %s", authType)
  97. }
  98. if len((*authParams)["service"]) == 0 {
  99. return nil, fmt.Errorf("Www-Authenticate: missing header \"service\"")
  100. }
  101. if len((*authParams)["realm"]) == 0 {
  102. return nil, fmt.Errorf("Www-Authenticate: missing header \"realm\"")
  103. }
  104. return &authDirective{
  105. service: (*authParams)["service"],
  106. realm: (*authParams)["realm"],
  107. }, nil
  108. }
  109. func performTokenExchange(
  110. serverAddress string,
  111. directive *authDirective,
  112. tenant string,
  113. accessToken string) (string, error) {
  114. var err error
  115. data := url.Values{
  116. "service": []string{directive.service},
  117. "grant_type": []string{"access_token_refresh_token"},
  118. "access_token": []string{accessToken},
  119. "refresh_token": []string{accessToken},
  120. "tenant": []string{tenant},
  121. }
  122. var realmURL *url.URL
  123. if realmURL, err = url.Parse(directive.realm); err != nil {
  124. return "", fmt.Errorf("Www-Authenticate: invalid realm %s", directive.realm)
  125. }
  126. authEndpoint := fmt.Sprintf("%s://%s/oauth2/exchange", realmURL.Scheme, realmURL.Host)
  127. datac := data.Encode()
  128. var r *http.Request
  129. r, _ = http.NewRequest("POST", authEndpoint, bytes.NewBufferString(datac))
  130. r.Header.Add(userAgentHeader, userAgent)
  131. r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  132. r.Header.Add("Content-Length", strconv.Itoa(len(datac)))
  133. var exchange *http.Response
  134. if exchange, err = client.Do(r); err != nil {
  135. return "", fmt.Errorf("Www-Authenticate: failed to reach auth url %s", authEndpoint)
  136. }
  137. defer exchange.Body.Close()
  138. if exchange.StatusCode != 200 {
  139. return "", fmt.Errorf("Www-Authenticate: auth url %s responded with status code %d", authEndpoint, exchange.StatusCode)
  140. }
  141. var content []byte
  142. limitedReader := &io.LimitedReader{R: exchange.Body, N: maxReadLength}
  143. if content, err = ioutil.ReadAll(limitedReader); err != nil {
  144. return "", fmt.Errorf("Www-Authenticate: error reading response from %s", authEndpoint)
  145. }
  146. if limitedReader.N <= 0 {
  147. return "", errors.New("the read limit is reached")
  148. }
  149. var authResp acrAuthResponse
  150. if err = json.Unmarshal(content, &authResp); err != nil {
  151. return "", fmt.Errorf("Www-Authenticate: unable to read response %s", content)
  152. }
  153. return authResp.RefreshToken, nil
  154. }
  155. // Try and parse a string of assignments in the form of:
  156. // key1 = value1, key2 = "value 2", key3 = ""
  157. // Note: this method and handle quotes but does not handle escaping of quotes
  158. func parseAssignments(statements string) (*map[string]string, error) {
  159. var cursor int
  160. result := make(map[string]string)
  161. var errorMsg = fmt.Errorf("malformed header value: %s", statements)
  162. for {
  163. // parse key
  164. equalIndex := nextOccurrence(statements, cursor, "=")
  165. if equalIndex == -1 {
  166. return nil, errorMsg
  167. }
  168. key := strings.TrimSpace(statements[cursor:equalIndex])
  169. // parse value
  170. cursor = nextNoneSpace(statements, equalIndex+1)
  171. if cursor == -1 {
  172. return nil, errorMsg
  173. }
  174. // case: value is quoted
  175. if statements[cursor] == '"' {
  176. cursor = cursor + 1
  177. // like I said, not handling escapes, but this will skip any comma that's
  178. // within the quotes which is somewhat more likely
  179. closeQuoteIndex := nextOccurrence(statements, cursor, "\"")
  180. if closeQuoteIndex == -1 {
  181. return nil, errorMsg
  182. }
  183. value := statements[cursor:closeQuoteIndex]
  184. result[key] = value
  185. commaIndex := nextNoneSpace(statements, closeQuoteIndex+1)
  186. if commaIndex == -1 {
  187. // no more comma, done
  188. return &result, nil
  189. } else if statements[commaIndex] != ',' {
  190. // expect comma immediately after close quote
  191. return nil, errorMsg
  192. } else {
  193. cursor = commaIndex + 1
  194. }
  195. } else {
  196. commaIndex := nextOccurrence(statements, cursor, ",")
  197. endStatements := commaIndex == -1
  198. var untrimmed string
  199. if endStatements {
  200. untrimmed = statements[cursor:commaIndex]
  201. } else {
  202. untrimmed = statements[cursor:]
  203. }
  204. value := strings.TrimSpace(untrimmed)
  205. if len(value) == 0 {
  206. // disallow empty value without quote
  207. return nil, errorMsg
  208. }
  209. result[key] = value
  210. if endStatements {
  211. return &result, nil
  212. }
  213. cursor = commaIndex + 1
  214. }
  215. }
  216. }
  217. func nextOccurrence(str string, start int, sep string) int {
  218. if start >= len(str) {
  219. return -1
  220. }
  221. offset := strings.Index(str[start:], sep)
  222. if offset == -1 {
  223. return -1
  224. }
  225. return offset + start
  226. }
  227. func nextNoneSpace(str string, start int) int {
  228. if start >= len(str) {
  229. return -1
  230. }
  231. offset := strings.IndexFunc(str[start:], func(c rune) bool { return !unicode.IsSpace(c) })
  232. if offset == -1 {
  233. return -1
  234. }
  235. return offset + start
  236. }