auth.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package oss
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "net/http"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. )
  16. // headerSorter defines the key-value structure for storing the sorted data in signHeader.
  17. type headerSorter struct {
  18. Keys []string
  19. Vals []string
  20. }
  21. // getAdditionalHeaderKeys get exist key in http header
  22. func (conn Conn) getAdditionalHeaderKeys(req *http.Request) ([]string, map[string]string) {
  23. var keysList []string
  24. keysMap := make(map[string]string)
  25. srcKeys := make(map[string]string)
  26. for k := range req.Header {
  27. srcKeys[strings.ToLower(k)] = ""
  28. }
  29. for _, v := range conn.config.AdditionalHeaders {
  30. if _, ok := srcKeys[strings.ToLower(v)]; ok {
  31. keysMap[strings.ToLower(v)] = ""
  32. }
  33. }
  34. for k := range keysMap {
  35. keysList = append(keysList, k)
  36. }
  37. sort.Strings(keysList)
  38. return keysList, keysMap
  39. }
  40. // signHeader signs the header and sets it as the authorization header.
  41. func (conn Conn) signHeader(req *http.Request, canonicalizedResource string) {
  42. akIf := conn.config.GetCredentials()
  43. authorizationStr := ""
  44. if conn.config.AuthVersion == AuthV2 {
  45. additionalList, _ := conn.getAdditionalHeaderKeys(req)
  46. if len(additionalList) > 0 {
  47. authorizationFmt := "OSS2 AccessKeyId:%v,AdditionalHeaders:%v,Signature:%v"
  48. additionnalHeadersStr := strings.Join(additionalList, ";")
  49. authorizationStr = fmt.Sprintf(authorizationFmt, akIf.GetAccessKeyID(), additionnalHeadersStr, conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret()))
  50. } else {
  51. authorizationFmt := "OSS2 AccessKeyId:%v,Signature:%v"
  52. authorizationStr = fmt.Sprintf(authorizationFmt, akIf.GetAccessKeyID(), conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret()))
  53. }
  54. } else {
  55. // Get the final authorization string
  56. authorizationStr = "OSS " + akIf.GetAccessKeyID() + ":" + conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret())
  57. }
  58. // Give the parameter "Authorization" value
  59. req.Header.Set(HTTPHeaderAuthorization, authorizationStr)
  60. }
  61. func (conn Conn) getSignedStr(req *http.Request, canonicalizedResource string, keySecret string) string {
  62. // Find out the "x-oss-"'s address in header of the request
  63. ossHeadersMap := make(map[string]string)
  64. additionalList, additionalMap := conn.getAdditionalHeaderKeys(req)
  65. for k, v := range req.Header {
  66. if strings.HasPrefix(strings.ToLower(k), "x-oss-") {
  67. ossHeadersMap[strings.ToLower(k)] = v[0]
  68. } else if conn.config.AuthVersion == AuthV2 {
  69. if _, ok := additionalMap[strings.ToLower(k)]; ok {
  70. ossHeadersMap[strings.ToLower(k)] = v[0]
  71. }
  72. }
  73. }
  74. hs := newHeaderSorter(ossHeadersMap)
  75. // Sort the ossHeadersMap by the ascending order
  76. hs.Sort()
  77. // Get the canonicalizedOSSHeaders
  78. canonicalizedOSSHeaders := ""
  79. for i := range hs.Keys {
  80. canonicalizedOSSHeaders += hs.Keys[i] + ":" + hs.Vals[i] + "\n"
  81. }
  82. // Give other parameters values
  83. // when sign URL, date is expires
  84. date := req.Header.Get(HTTPHeaderDate)
  85. contentType := req.Header.Get(HTTPHeaderContentType)
  86. contentMd5 := req.Header.Get(HTTPHeaderContentMD5)
  87. // default is v1 signature
  88. signStr := req.Method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource
  89. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(keySecret))
  90. // v2 signature
  91. if conn.config.AuthVersion == AuthV2 {
  92. signStr = req.Method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + strings.Join(additionalList, ";") + "\n" + canonicalizedResource
  93. h = hmac.New(func() hash.Hash { return sha256.New() }, []byte(keySecret))
  94. }
  95. // convert sign to log for easy to view
  96. if conn.config.LogLevel >= Debug {
  97. var signBuf bytes.Buffer
  98. for i := 0; i < len(signStr); i++ {
  99. if signStr[i] != '\n' {
  100. signBuf.WriteByte(signStr[i])
  101. } else {
  102. signBuf.WriteString("\\n")
  103. }
  104. }
  105. conn.config.WriteLog(Debug, "[Req:%p]signStr:%s\n", req, signBuf.String())
  106. }
  107. io.WriteString(h, signStr)
  108. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  109. return signedStr
  110. }
  111. func (conn Conn) getRtmpSignedStr(bucketName, channelName, playlistName string, expiration int64, keySecret string, params map[string]interface{}) string {
  112. if params[HTTPParamAccessKeyID] == nil {
  113. return ""
  114. }
  115. canonResource := fmt.Sprintf("/%s/%s", bucketName, channelName)
  116. canonParamsKeys := []string{}
  117. for key := range params {
  118. if key != HTTPParamAccessKeyID && key != HTTPParamSignature && key != HTTPParamExpires && key != HTTPParamSecurityToken {
  119. canonParamsKeys = append(canonParamsKeys, key)
  120. }
  121. }
  122. sort.Strings(canonParamsKeys)
  123. canonParamsStr := ""
  124. for _, key := range canonParamsKeys {
  125. canonParamsStr = fmt.Sprintf("%s%s:%s\n", canonParamsStr, key, params[key].(string))
  126. }
  127. expireStr := strconv.FormatInt(expiration, 10)
  128. signStr := expireStr + "\n" + canonParamsStr + canonResource
  129. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(keySecret))
  130. io.WriteString(h, signStr)
  131. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  132. return signedStr
  133. }
  134. // newHeaderSorter is an additional function for function SignHeader.
  135. func newHeaderSorter(m map[string]string) *headerSorter {
  136. hs := &headerSorter{
  137. Keys: make([]string, 0, len(m)),
  138. Vals: make([]string, 0, len(m)),
  139. }
  140. for k, v := range m {
  141. hs.Keys = append(hs.Keys, k)
  142. hs.Vals = append(hs.Vals, v)
  143. }
  144. return hs
  145. }
  146. // Sort is an additional function for function SignHeader.
  147. func (hs *headerSorter) Sort() {
  148. sort.Sort(hs)
  149. }
  150. // Len is an additional function for function SignHeader.
  151. func (hs *headerSorter) Len() int {
  152. return len(hs.Vals)
  153. }
  154. // Less is an additional function for function SignHeader.
  155. func (hs *headerSorter) Less(i, j int) bool {
  156. return bytes.Compare([]byte(hs.Keys[i]), []byte(hs.Keys[j])) < 0
  157. }
  158. // Swap is an additional function for function SignHeader.
  159. func (hs *headerSorter) Swap(i, j int) {
  160. hs.Vals[i], hs.Vals[j] = hs.Vals[j], hs.Vals[i]
  161. hs.Keys[i], hs.Keys[j] = hs.Keys[j], hs.Keys[i]
  162. }