chunked_reader_v4.go 11 KB

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