chunked_reader_v4.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package s3api
  2. // the related code is copied and modified from minio source code
  3. /*
  4. * Minio Cloud Storage, (C) 2016 Minio, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. import (
  19. "bufio"
  20. "bytes"
  21. "crypto/sha256"
  22. "encoding/hex"
  23. "errors"
  24. "hash"
  25. "io"
  26. "net/http"
  27. "time"
  28. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  29. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  30. "github.com/dustin/go-humanize"
  31. )
  32. // calculateSeedSignature - Calculate seed signature in accordance with
  33. // - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
  34. //
  35. // returns signature, error otherwise if the signature mismatches or any other
  36. // error while parsing and validating.
  37. func (iam *IdentityAccessManagement) calculateSeedSignature(r *http.Request) (cred *Credential, signature string, region string, date time.Time, errCode s3err.ErrorCode) {
  38. // Copy request.
  39. req := *r
  40. // Save authorization header.
  41. v4Auth := req.Header.Get("Authorization")
  42. // Parse signature version '4' header.
  43. signV4Values, errCode := parseSignV4(v4Auth)
  44. if errCode != s3err.ErrNone {
  45. return nil, "", "", time.Time{}, errCode
  46. }
  47. // Payload streaming.
  48. payload := streamingContentSHA256
  49. // Payload for STREAMING signature should be 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD'
  50. if payload != req.Header.Get("X-Amz-Content-Sha256") {
  51. return nil, "", "", time.Time{}, s3err.ErrContentSHA256Mismatch
  52. }
  53. // Extract all the signed headers along with its values.
  54. extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
  55. if errCode != s3err.ErrNone {
  56. return nil, "", "", time.Time{}, errCode
  57. }
  58. // Verify if the access key id matches.
  59. identity, cred, found := iam.lookupByAccessKey(signV4Values.Credential.accessKey)
  60. if !found {
  61. return nil, "", "", time.Time{}, s3err.ErrInvalidAccessKeyID
  62. }
  63. bucket, object := s3_constants.GetBucketAndObject(r)
  64. if !identity.canDo(s3_constants.ACTION_WRITE, bucket, object) {
  65. errCode = s3err.ErrAccessDenied
  66. return
  67. }
  68. // Verify if region is valid.
  69. region = signV4Values.Credential.scope.region
  70. // Extract date, if not present throw error.
  71. var dateStr string
  72. if dateStr = req.Header.Get(http.CanonicalHeaderKey("x-amz-date")); dateStr == "" {
  73. if dateStr = r.Header.Get("Date"); dateStr == "" {
  74. return nil, "", "", time.Time{}, s3err.ErrMissingDateHeader
  75. }
  76. }
  77. // Parse date header.
  78. var err error
  79. date, err = time.Parse(iso8601Format, dateStr)
  80. if err != nil {
  81. return nil, "", "", time.Time{}, s3err.ErrMalformedDate
  82. }
  83. // Query string.
  84. queryStr := req.URL.Query().Encode()
  85. // Get canonical request.
  86. canonicalRequest := getCanonicalRequest(extractedSignedHeaders, payload, queryStr, req.URL.Path, req.Method)
  87. // Get string to sign from canonical request.
  88. stringToSign := getStringToSign(canonicalRequest, date, signV4Values.Credential.getScope())
  89. // Calculate signature.
  90. newSignature := iam.getSignature(
  91. cred.SecretKey,
  92. signV4Values.Credential.scope.date,
  93. region,
  94. "s3",
  95. stringToSign,
  96. )
  97. // Verify if signature match.
  98. if !compareSignatureV4(newSignature, signV4Values.Signature) {
  99. return nil, "", "", time.Time{}, s3err.ErrSignatureDoesNotMatch
  100. }
  101. // Return calculated signature.
  102. return cred, newSignature, region, date, s3err.ErrNone
  103. }
  104. const maxLineLength = 4 * humanize.KiByte // assumed <= bufio.defaultBufSize 4KiB
  105. // lineTooLong is generated as chunk header is bigger than 4KiB.
  106. var errLineTooLong = errors.New("header line too long")
  107. // Malformed encoding is generated when chunk header is wrongly formed.
  108. var errMalformedEncoding = errors.New("malformed chunked encoding")
  109. // newSignV4ChunkedReader returns a new s3ChunkedReader that translates the data read from r
  110. // out of HTTP "chunked" format before returning it.
  111. // The s3ChunkedReader returns io.EOF when the final 0-length chunk is read.
  112. func (iam *IdentityAccessManagement) newSignV4ChunkedReader(req *http.Request) (io.ReadCloser, s3err.ErrorCode) {
  113. ident, seedSignature, region, seedDate, errCode := iam.calculateSeedSignature(req)
  114. if errCode != s3err.ErrNone {
  115. return nil, errCode
  116. }
  117. return &s3ChunkedReader{
  118. cred: ident,
  119. reader: bufio.NewReader(req.Body),
  120. seedSignature: seedSignature,
  121. seedDate: seedDate,
  122. region: region,
  123. chunkSHA256Writer: sha256.New(),
  124. state: readChunkHeader,
  125. iam: iam,
  126. }, s3err.ErrNone
  127. }
  128. // Represents the overall state that is required for decoding a
  129. // AWS Signature V4 chunked reader.
  130. type s3ChunkedReader struct {
  131. cred *Credential
  132. reader *bufio.Reader
  133. seedSignature string
  134. seedDate time.Time
  135. region string
  136. state chunkState
  137. lastChunk bool
  138. chunkSignature string
  139. chunkSHA256Writer hash.Hash // Calculates sha256 of chunk data.
  140. n uint64 // Unread bytes in chunk
  141. err error
  142. iam *IdentityAccessManagement
  143. }
  144. // Read chunk reads the chunk token signature portion.
  145. func (cr *s3ChunkedReader) readS3ChunkHeader() {
  146. // Read the first chunk line until CRLF.
  147. var hexChunkSize, hexChunkSignature []byte
  148. hexChunkSize, hexChunkSignature, cr.err = readChunkLine(cr.reader)
  149. if cr.err != nil {
  150. return
  151. }
  152. // <hex>;token=value - converts the hex into its uint64 form.
  153. cr.n, cr.err = parseHexUint(hexChunkSize)
  154. if cr.err != nil {
  155. return
  156. }
  157. if cr.n == 0 {
  158. cr.err = io.EOF
  159. }
  160. // Save the incoming chunk signature.
  161. cr.chunkSignature = string(hexChunkSignature)
  162. }
  163. type chunkState int
  164. const (
  165. readChunkHeader chunkState = iota
  166. readChunkTrailer
  167. readChunk
  168. verifyChunk
  169. eofChunk
  170. )
  171. func (cs chunkState) String() string {
  172. stateString := ""
  173. switch cs {
  174. case readChunkHeader:
  175. stateString = "readChunkHeader"
  176. case readChunkTrailer:
  177. stateString = "readChunkTrailer"
  178. case readChunk:
  179. stateString = "readChunk"
  180. case verifyChunk:
  181. stateString = "verifyChunk"
  182. case eofChunk:
  183. stateString = "eofChunk"
  184. }
  185. return stateString
  186. }
  187. func (cr *s3ChunkedReader) Close() (err error) {
  188. return nil
  189. }
  190. // Read - implements `io.Reader`, which transparently decodes
  191. // the incoming AWS Signature V4 streaming signature.
  192. func (cr *s3ChunkedReader) Read(buf []byte) (n int, err error) {
  193. for {
  194. switch cr.state {
  195. case readChunkHeader:
  196. cr.readS3ChunkHeader()
  197. // If we're at the end of a chunk.
  198. if cr.n == 0 && cr.err == io.EOF {
  199. cr.state = readChunkTrailer
  200. cr.lastChunk = true
  201. continue
  202. }
  203. if cr.err != nil {
  204. return 0, cr.err
  205. }
  206. cr.state = readChunk
  207. case readChunkTrailer:
  208. cr.err = readCRLF(cr.reader)
  209. if cr.err != nil {
  210. return 0, errMalformedEncoding
  211. }
  212. cr.state = verifyChunk
  213. case readChunk:
  214. // There is no more space left in the request buffer.
  215. if len(buf) == 0 {
  216. return n, nil
  217. }
  218. rbuf := buf
  219. // The request buffer is larger than the current chunk size.
  220. // Read only the current chunk from the underlying reader.
  221. if uint64(len(rbuf)) > cr.n {
  222. rbuf = rbuf[:cr.n]
  223. }
  224. var n0 int
  225. n0, cr.err = cr.reader.Read(rbuf)
  226. if cr.err != nil {
  227. // We have lesser than chunk size advertised in chunkHeader, this is 'unexpected'.
  228. if cr.err == io.EOF {
  229. cr.err = io.ErrUnexpectedEOF
  230. }
  231. return 0, cr.err
  232. }
  233. // Calculate sha256.
  234. cr.chunkSHA256Writer.Write(rbuf[:n0])
  235. // Update the bytes read into request buffer so far.
  236. n += n0
  237. buf = buf[n0:]
  238. // Update bytes to be read of the current chunk before verifying chunk's signature.
  239. cr.n -= uint64(n0)
  240. // If we're at the end of a chunk.
  241. if cr.n == 0 {
  242. cr.state = readChunkTrailer
  243. continue
  244. }
  245. case verifyChunk:
  246. // Calculate the hashed chunk.
  247. hashedChunk := hex.EncodeToString(cr.chunkSHA256Writer.Sum(nil))
  248. // Calculate the chunk signature.
  249. newSignature := cr.getChunkSignature(hashedChunk)
  250. if !compareSignatureV4(cr.chunkSignature, newSignature) {
  251. // Chunk signature doesn't match we return signature does not match.
  252. cr.err = errors.New("chunk signature does not match")
  253. return 0, cr.err
  254. }
  255. // Newly calculated signature becomes the seed for the next chunk
  256. // this follows the chaining.
  257. cr.seedSignature = newSignature
  258. cr.chunkSHA256Writer.Reset()
  259. if cr.lastChunk {
  260. cr.state = eofChunk
  261. } else {
  262. cr.state = readChunkHeader
  263. }
  264. case eofChunk:
  265. return n, io.EOF
  266. }
  267. }
  268. }
  269. // getChunkSignature - get chunk signature.
  270. func (cr *s3ChunkedReader) getChunkSignature(hashedChunk string) string {
  271. // Calculate string to sign.
  272. stringToSign := signV4ChunkedAlgorithm + "\n" +
  273. cr.seedDate.Format(iso8601Format) + "\n" +
  274. getScope(cr.seedDate, cr.region) + "\n" +
  275. cr.seedSignature + "\n" +
  276. emptySHA256 + "\n" +
  277. hashedChunk
  278. // Calculate signature.
  279. return cr.iam.getSignature(
  280. cr.cred.SecretKey,
  281. cr.seedDate,
  282. cr.region,
  283. "s3",
  284. stringToSign,
  285. )
  286. }
  287. // readCRLF - check if reader only has '\r\n' CRLF character.
  288. // returns malformed encoding if it doesn't.
  289. func readCRLF(reader io.Reader) error {
  290. buf := make([]byte, 2)
  291. _, err := io.ReadFull(reader, buf[:2])
  292. if err != nil {
  293. return err
  294. }
  295. if buf[0] != '\r' || buf[1] != '\n' {
  296. return errMalformedEncoding
  297. }
  298. return nil
  299. }
  300. // Read a line of bytes (up to \n) from b.
  301. // Give up if the line exceeds maxLineLength.
  302. // The returned bytes are owned by the bufio.Reader
  303. // so they are only valid until the next bufio read.
  304. func readChunkLine(b *bufio.Reader) ([]byte, []byte, error) {
  305. buf, err := b.ReadSlice('\n')
  306. if err != nil {
  307. // We always know when EOF is coming.
  308. // If the caller asked for a line, there should be a line.
  309. if err == io.EOF {
  310. err = io.ErrUnexpectedEOF
  311. } else if err == bufio.ErrBufferFull {
  312. err = errLineTooLong
  313. }
  314. return nil, nil, err
  315. }
  316. if len(buf) >= maxLineLength {
  317. return nil, nil, errLineTooLong
  318. }
  319. // Parse s3 specific chunk extension and fetch the values.
  320. hexChunkSize, hexChunkSignature := parseS3ChunkExtension(buf)
  321. return hexChunkSize, hexChunkSignature, nil
  322. }
  323. // trimTrailingWhitespace - trim trailing white space.
  324. func trimTrailingWhitespace(b []byte) []byte {
  325. for len(b) > 0 && isASCIISpace(b[len(b)-1]) {
  326. b = b[:len(b)-1]
  327. }
  328. return b
  329. }
  330. // isASCIISpace - is ascii space?
  331. func isASCIISpace(b byte) bool {
  332. return b == ' ' || b == '\t' || b == '\n' || b == '\r'
  333. }
  334. // Constant s3 chunk encoding signature.
  335. const s3ChunkSignatureStr = ";chunk-signature="
  336. // parses3ChunkExtension removes any s3 specific chunk-extension from buf.
  337. // For example,
  338. //
  339. // "10000;chunk-signature=..." => "10000", "chunk-signature=..."
  340. func parseS3ChunkExtension(buf []byte) ([]byte, []byte) {
  341. buf = trimTrailingWhitespace(buf)
  342. semi := bytes.Index(buf, []byte(s3ChunkSignatureStr))
  343. // Chunk signature not found, return the whole buffer.
  344. if semi == -1 {
  345. return buf, nil
  346. }
  347. return buf[:semi], parseChunkSignature(buf[semi:])
  348. }
  349. // parseChunkSignature - parse chunk signature.
  350. func parseChunkSignature(chunk []byte) []byte {
  351. chunkSplits := bytes.SplitN(chunk, []byte(s3ChunkSignatureStr), 2)
  352. return chunkSplits[1]
  353. }
  354. // parse hex to uint64.
  355. func parseHexUint(v []byte) (n uint64, err error) {
  356. for i, b := range v {
  357. switch {
  358. case '0' <= b && b <= '9':
  359. b = b - '0'
  360. case 'a' <= b && b <= 'f':
  361. b = b - 'a' + 10
  362. case 'A' <= b && b <= 'F':
  363. b = b - 'A' + 10
  364. default:
  365. return 0, errors.New("invalid byte in chunk length")
  366. }
  367. if i == 16 {
  368. return 0, errors.New("http chunk length too large")
  369. }
  370. n <<= 4
  371. n |= uint64(b)
  372. }
  373. return
  374. }