You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
392 lines
13 KiB
392 lines
13 KiB
10 years ago
|
/*
|
||
10 years ago
|
* Minio Cloud Storage, (C) 2015 Minio, Inc.
|
||
10 years ago
|
*
|
||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||
|
* you may not use this file except in compliance with the License.
|
||
|
* You may obtain a copy of the License at
|
||
|
*
|
||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||
|
*
|
||
|
* Unless required by applicable law or agreed to in writing, software
|
||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
|
* See the License for the specific language governing permissions and
|
||
|
* limitations under the License.
|
||
|
*/
|
||
|
|
||
9 years ago
|
// Package signature4 implements helper functions to validate AWS
|
||
|
// Signature Version '4' authorization header.
|
||
|
//
|
||
|
// This package provides comprehensive helpers for following signature
|
||
|
// types.
|
||
|
// - Based on Authorization header.
|
||
|
// - Based on Query parameters.
|
||
|
// - Based on Form POST policy.
|
||
|
package signature4
|
||
10 years ago
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/hex"
|
||
|
"net/http"
|
||
9 years ago
|
"net/url"
|
||
10 years ago
|
"sort"
|
||
9 years ago
|
"strconv"
|
||
10 years ago
|
"strings"
|
||
|
"time"
|
||
|
|
||
9 years ago
|
"github.com/minio/minio/pkg/crypto/sha256"
|
||
|
"github.com/minio/minio/pkg/probe"
|
||
10 years ago
|
)
|
||
|
|
||
9 years ago
|
// Sign - local variables
|
||
|
type Sign struct {
|
||
9 years ago
|
accessKeyID string
|
||
|
secretAccessKey string
|
||
|
region string
|
||
|
httpRequest *http.Request
|
||
|
extractedSignedHeaders http.Header
|
||
10 years ago
|
}
|
||
|
|
||
9 years ago
|
// AWS Signature Version '4' constants.
|
||
10 years ago
|
const (
|
||
9 years ago
|
signV4Algorithm = "AWS4-HMAC-SHA256"
|
||
|
iso8601Format = "20060102T150405Z"
|
||
|
yyyymmdd = "20060102"
|
||
10 years ago
|
)
|
||
|
|
||
9 years ago
|
// New - initialize a new authorization checkes.
|
||
9 years ago
|
func New(accessKeyID, secretAccessKey, region string) (*Sign, *probe.Error) {
|
||
9 years ago
|
if !isValidAccessKey.MatchString(accessKeyID) {
|
||
|
return nil, ErrInvalidAccessKeyID("Invalid access key id.", accessKeyID).Trace(accessKeyID)
|
||
|
}
|
||
|
if !isValidSecretKey.MatchString(secretAccessKey) {
|
||
|
return nil, ErrInvalidAccessKeyID("Invalid secret key.", secretAccessKey).Trace(secretAccessKey)
|
||
|
}
|
||
|
if region == "" {
|
||
|
return nil, ErrRegionISEmpty("Region is empty.").Trace()
|
||
|
}
|
||
9 years ago
|
signature := &Sign{
|
||
9 years ago
|
accessKeyID: accessKeyID,
|
||
|
secretAccessKey: secretAccessKey,
|
||
|
region: region,
|
||
|
}
|
||
|
return signature, nil
|
||
10 years ago
|
}
|
||
|
|
||
9 years ago
|
// SetHTTPRequestToVerify - sets the http request which needs to be verified.
|
||
9 years ago
|
func (s *Sign) SetHTTPRequestToVerify(r *http.Request) *Sign {
|
||
9 years ago
|
// Do not set http request if its 'nil'.
|
||
|
if r == nil {
|
||
|
return s
|
||
10 years ago
|
}
|
||
9 years ago
|
s.httpRequest = r
|
||
|
return s
|
||
10 years ago
|
}
|
||
|
|
||
|
// getCanonicalHeaders generate a list of request headers with their values
|
||
9 years ago
|
func (s Sign) getCanonicalHeaders(signedHeaders http.Header) string {
|
||
10 years ago
|
var headers []string
|
||
9 years ago
|
vals := make(http.Header)
|
||
10 years ago
|
for k, vv := range signedHeaders {
|
||
10 years ago
|
headers = append(headers, strings.ToLower(k))
|
||
|
vals[strings.ToLower(k)] = vv
|
||
|
}
|
||
|
headers = append(headers, "host")
|
||
|
sort.Strings(headers)
|
||
|
|
||
|
var buf bytes.Buffer
|
||
|
for _, k := range headers {
|
||
|
buf.WriteString(k)
|
||
|
buf.WriteByte(':')
|
||
|
switch {
|
||
|
case k == "host":
|
||
9 years ago
|
buf.WriteString(s.httpRequest.Host)
|
||
10 years ago
|
fallthrough
|
||
|
default:
|
||
|
for idx, v := range vals[k] {
|
||
|
if idx > 0 {
|
||
|
buf.WriteByte(',')
|
||
|
}
|
||
|
buf.WriteString(v)
|
||
|
}
|
||
|
buf.WriteByte('\n')
|
||
|
}
|
||
|
}
|
||
|
return buf.String()
|
||
|
}
|
||
|
|
||
|
// getSignedHeaders generate a string i.e alphabetically sorted, semicolon-separated list of lowercase request header names
|
||
9 years ago
|
func (s Sign) getSignedHeaders(signedHeaders http.Header) string {
|
||
10 years ago
|
var headers []string
|
||
10 years ago
|
for k := range signedHeaders {
|
||
10 years ago
|
headers = append(headers, strings.ToLower(k))
|
||
|
}
|
||
|
headers = append(headers, "host")
|
||
|
sort.Strings(headers)
|
||
|
return strings.Join(headers, ";")
|
||
|
}
|
||
|
|
||
|
// getCanonicalRequest generate a canonical request of style
|
||
|
//
|
||
|
// canonicalRequest =
|
||
|
// <HTTPMethod>\n
|
||
|
// <CanonicalURI>\n
|
||
|
// <CanonicalQueryString>\n
|
||
|
// <CanonicalHeaders>\n
|
||
|
// <SignedHeaders>\n
|
||
|
// <HashedPayload>
|
||
|
//
|
||
9 years ago
|
func (s *Sign) getCanonicalRequest() string {
|
||
9 years ago
|
payload := s.httpRequest.Header.Get(http.CanonicalHeaderKey("x-amz-content-sha256"))
|
||
|
s.httpRequest.URL.RawQuery = strings.Replace(s.httpRequest.URL.Query().Encode(), "+", "%20", -1)
|
||
|
encodedPath := getURLEncodedName(s.httpRequest.URL.Path)
|
||
|
// Convert any space strings back to "+".
|
||
10 years ago
|
encodedPath = strings.Replace(encodedPath, "+", "%20", -1)
|
||
|
canonicalRequest := strings.Join([]string{
|
||
9 years ago
|
s.httpRequest.Method,
|
||
10 years ago
|
encodedPath,
|
||
9 years ago
|
s.httpRequest.URL.RawQuery,
|
||
|
s.getCanonicalHeaders(s.extractedSignedHeaders),
|
||
|
s.getSignedHeaders(s.extractedSignedHeaders),
|
||
9 years ago
|
payload,
|
||
|
}, "\n")
|
||
|
return canonicalRequest
|
||
|
}
|
||
|
|
||
|
// getCanonicalRequest generate a canonical request of style
|
||
|
//
|
||
|
// canonicalRequest =
|
||
|
// <HTTPMethod>\n
|
||
|
// <CanonicalURI>\n
|
||
|
// <CanonicalQueryString>\n
|
||
|
// <CanonicalHeaders>\n
|
||
|
// <SignedHeaders>\n
|
||
|
// <HashedPayload>
|
||
|
//
|
||
9 years ago
|
func (s Sign) getPresignedCanonicalRequest(presignedQuery string) string {
|
||
9 years ago
|
rawQuery := strings.Replace(presignedQuery, "+", "%20", -1)
|
||
9 years ago
|
encodedPath := getURLEncodedName(s.httpRequest.URL.Path)
|
||
|
// Convert any space strings back to "+".
|
||
9 years ago
|
encodedPath = strings.Replace(encodedPath, "+", "%20", -1)
|
||
|
canonicalRequest := strings.Join([]string{
|
||
9 years ago
|
s.httpRequest.Method,
|
||
9 years ago
|
encodedPath,
|
||
|
rawQuery,
|
||
9 years ago
|
s.getCanonicalHeaders(s.extractedSignedHeaders),
|
||
|
s.getSignedHeaders(s.extractedSignedHeaders),
|
||
9 years ago
|
"UNSIGNED-PAYLOAD",
|
||
10 years ago
|
}, "\n")
|
||
|
return canonicalRequest
|
||
|
}
|
||
|
|
||
9 years ago
|
// getScope generate a string of a specific date, an AWS region, and a service.
|
||
9 years ago
|
func (s Sign) getScope(t time.Time) string {
|
||
10 years ago
|
scope := strings.Join([]string{
|
||
|
t.Format(yyyymmdd),
|
||
9 years ago
|
s.region,
|
||
10 years ago
|
"s3",
|
||
|
"aws4_request",
|
||
|
}, "/")
|
||
|
return scope
|
||
|
}
|
||
|
|
||
9 years ago
|
// getStringToSign a string based on selected query values.
|
||
9 years ago
|
func (s Sign) getStringToSign(canonicalRequest string, t time.Time) string {
|
||
9 years ago
|
stringToSign := signV4Algorithm + "\n" + t.Format(iso8601Format) + "\n"
|
||
|
stringToSign = stringToSign + s.getScope(t) + "\n"
|
||
9 years ago
|
canonicalRequestBytes := sha256.Sum256([]byte(canonicalRequest))
|
||
|
stringToSign = stringToSign + hex.EncodeToString(canonicalRequestBytes[:])
|
||
10 years ago
|
return stringToSign
|
||
|
}
|
||
|
|
||
9 years ago
|
// getSigningKey hmac seed to calculate final signature.
|
||
9 years ago
|
func (s Sign) getSigningKey(t time.Time) []byte {
|
||
9 years ago
|
secret := s.secretAccessKey
|
||
10 years ago
|
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
|
||
9 years ago
|
region := sumHMAC(date, []byte(s.region))
|
||
10 years ago
|
service := sumHMAC(region, []byte("s3"))
|
||
|
signingKey := sumHMAC(service, []byte("aws4_request"))
|
||
|
return signingKey
|
||
|
}
|
||
|
|
||
9 years ago
|
// getSignature final signature in hexadecimal form.
|
||
9 years ago
|
func (s Sign) getSignature(signingKey []byte, stringToSign string) string {
|
||
10 years ago
|
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
|
||
|
}
|
||
|
|
||
9 years ago
|
// DoesPolicySignatureMatch - Verify query headers with post policy
|
||
|
// - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
|
||
|
// returns true if matches, false otherwise. if error is not nil then it is always false
|
||
9 years ago
|
func (s *Sign) DoesPolicySignatureMatch(formValues map[string]string) (bool, *probe.Error) {
|
||
9 years ago
|
// Parse credential tag.
|
||
9 years ago
|
credential, err := parseCredential("Credential=" + formValues["X-Amz-Credential"])
|
||
9 years ago
|
if err != nil {
|
||
9 years ago
|
return false, err.Trace(formValues["X-Amz-Credential"])
|
||
|
}
|
||
|
|
||
|
// Verify if the access key id matches.
|
||
9 years ago
|
if credential.accessKeyID != s.accessKeyID {
|
||
|
return false, ErrInvalidAccessKeyID("Access key id does not match with our records.", credential.accessKeyID).Trace(credential.accessKeyID)
|
||
9 years ago
|
}
|
||
|
|
||
|
// Verify if the region is valid.
|
||
9 years ago
|
reqRegion := credential.scope.region
|
||
9 years ago
|
if !isValidRegion(reqRegion, s.region) {
|
||
|
return false, ErrInvalidRegion("Requested region is not recognized.", reqRegion).Trace(reqRegion)
|
||
|
}
|
||
|
|
||
|
// Save region.
|
||
|
s.region = reqRegion
|
||
|
|
||
|
// Parse date string.
|
||
|
t, e := time.Parse(iso8601Format, formValues["X-Amz-Date"])
|
||
|
if e != nil {
|
||
|
return false, probe.NewError(e)
|
||
9 years ago
|
}
|
||
9 years ago
|
signingKey := s.getSigningKey(t)
|
||
|
newSignature := s.getSignature(signingKey, formValues["Policy"])
|
||
|
if newSignature != formValues["X-Amz-Signature"] {
|
||
9 years ago
|
return false, nil
|
||
|
}
|
||
9 years ago
|
return true, nil
|
||
|
}
|
||
|
|
||
|
// DoesPresignedSignatureMatch - Verify query headers with presigned signature
|
||
|
// - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
|
||
|
// returns true if matches, false otherwise. if error is not nil then it is always false
|
||
9 years ago
|
func (s *Sign) DoesPresignedSignatureMatch() (bool, *probe.Error) {
|
||
9 years ago
|
// Parse request query string.
|
||
9 years ago
|
preSignValues, err := parsePreSignV4(s.httpRequest.URL.Query())
|
||
9 years ago
|
if err != nil {
|
||
9 years ago
|
return false, err.Trace(s.httpRequest.URL.String())
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
|
// Verify if the access key id matches.
|
||
9 years ago
|
if preSignValues.Credential.accessKeyID != s.accessKeyID {
|
||
|
return false, ErrInvalidAccessKeyID("Access key id does not match with our records.", preSignValues.Credential.accessKeyID).Trace(preSignValues.Credential.accessKeyID)
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
|
// Verify if region is valid.
|
||
9 years ago
|
reqRegion := preSignValues.Credential.scope.region
|
||
9 years ago
|
if !isValidRegion(reqRegion, s.region) {
|
||
|
return false, ErrInvalidRegion("Requested region is not recognized.", reqRegion).Trace(reqRegion)
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
|
// Save region.
|
||
|
s.region = reqRegion
|
||
|
|
||
|
// Extract all the signed headers along with its values.
|
||
9 years ago
|
s.extractedSignedHeaders = extractSignedHeaders(preSignValues.SignedHeaders, s.httpRequest.Header)
|
||
9 years ago
|
|
||
|
// Construct new query.
|
||
|
query := make(url.Values)
|
||
|
query.Set("X-Amz-Algorithm", signV4Algorithm)
|
||
|
|
||
9 years ago
|
if time.Now().UTC().Sub(preSignValues.Date) > time.Duration(preSignValues.Expires) {
|
||
9 years ago
|
return false, ErrExpiredPresignRequest("Presigned request already expired, please initiate a new request.")
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
|
// Save the date and expires.
|
||
9 years ago
|
t := preSignValues.Date
|
||
|
expireSeconds := int(time.Duration(preSignValues.Expires) / time.Second)
|
||
9 years ago
|
|
||
9 years ago
|
// Construct the query.
|
||
9 years ago
|
query.Set("X-Amz-Date", t.Format(iso8601Format))
|
||
|
query.Set("X-Amz-Expires", strconv.Itoa(expireSeconds))
|
||
9 years ago
|
query.Set("X-Amz-SignedHeaders", s.getSignedHeaders(s.extractedSignedHeaders))
|
||
|
query.Set("X-Amz-Credential", s.accessKeyID+"/"+s.getScope(t))
|
||
9 years ago
|
|
||
|
// Save other headers available in the request parameters.
|
||
9 years ago
|
for k, v := range s.httpRequest.URL.Query() {
|
||
9 years ago
|
if strings.HasPrefix(strings.ToLower(k), "x-amz") {
|
||
|
continue
|
||
|
}
|
||
|
query[k] = v
|
||
|
}
|
||
9 years ago
|
|
||
|
// Get the encoded query.
|
||
9 years ago
|
encodedQuery := query.Encode()
|
||
|
|
||
9 years ago
|
// Verify if date query is same.
|
||
9 years ago
|
if s.httpRequest.URL.Query().Get("X-Amz-Date") != query.Get("X-Amz-Date") {
|
||
9 years ago
|
return false, nil
|
||
|
}
|
||
|
// Verify if expires query is same.
|
||
9 years ago
|
if s.httpRequest.URL.Query().Get("X-Amz-Expires") != query.Get("X-Amz-Expires") {
|
||
9 years ago
|
return false, nil
|
||
|
}
|
||
|
// Verify if signed headers query is same.
|
||
9 years ago
|
if s.httpRequest.URL.Query().Get("X-Amz-SignedHeaders") != query.Get("X-Amz-SignedHeaders") {
|
||
9 years ago
|
return false, nil
|
||
|
}
|
||
|
// Verify if credential query is same.
|
||
9 years ago
|
if s.httpRequest.URL.Query().Get("X-Amz-Credential") != query.Get("X-Amz-Credential") {
|
||
9 years ago
|
return false, nil
|
||
|
}
|
||
|
// Verify finally if signature is same.
|
||
9 years ago
|
newSignature := s.getSignature(s.getSigningKey(t), s.getStringToSign(s.getPresignedCanonicalRequest(encodedQuery), t))
|
||
|
if s.httpRequest.URL.Query().Get("X-Amz-Signature") != newSignature {
|
||
9 years ago
|
return false, nil
|
||
|
}
|
||
|
return true, nil
|
||
|
}
|
||
|
|
||
|
// DoesSignatureMatch - Verify authorization header with calculated header in accordance with
|
||
|
// - http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
|
||
|
// returns true if matches, false otherwise. if error is not nil then it is always false
|
||
9 years ago
|
func (s *Sign) DoesSignatureMatch(hashedPayload string) (bool, *probe.Error) {
|
||
9 years ago
|
// Save authorization header.
|
||
|
v4Auth := s.httpRequest.Header.Get("Authorization")
|
||
|
|
||
|
// Parse signature version '4' header.
|
||
|
signV4Values, err := parseSignV4(v4Auth)
|
||
|
if err != nil {
|
||
|
return false, err.Trace(v4Auth)
|
||
|
}
|
||
|
|
||
|
// Extract all the signed headers along with its values.
|
||
|
s.extractedSignedHeaders = extractSignedHeaders(signV4Values.SignedHeaders, s.httpRequest.Header)
|
||
|
|
||
|
// Verify if the access key id matches.
|
||
9 years ago
|
if signV4Values.Credential.accessKeyID != s.accessKeyID {
|
||
|
return false, ErrInvalidAccessKeyID("Access key id does not match with our records.", signV4Values.Credential.accessKeyID).Trace(signV4Values.Credential.accessKeyID)
|
||
9 years ago
|
}
|
||
10 years ago
|
|
||
9 years ago
|
// Verify if region is valid.
|
||
9 years ago
|
reqRegion := signV4Values.Credential.scope.region
|
||
9 years ago
|
if !isValidRegion(reqRegion, s.region) {
|
||
|
return false, ErrInvalidRegion("Requested region is not recognized.", reqRegion).Trace(reqRegion)
|
||
|
}
|
||
|
|
||
|
// Save region.
|
||
|
s.region = reqRegion
|
||
|
|
||
|
// Set input payload.
|
||
|
s.httpRequest.Header.Set("X-Amz-Content-Sha256", hashedPayload)
|
||
|
|
||
|
// Extract date, if not present throw error.
|
||
10 years ago
|
var date string
|
||
9 years ago
|
if date = s.httpRequest.Header.Get(http.CanonicalHeaderKey("x-amz-date")); date == "" {
|
||
|
if date = s.httpRequest.Header.Get("Date"); date == "" {
|
||
|
return false, ErrMissingDateHeader("Date header is missing from the request.").Trace()
|
||
10 years ago
|
}
|
||
|
}
|
||
9 years ago
|
// Parse date header.
|
||
|
t, e := time.Parse(iso8601Format, date)
|
||
|
if e != nil {
|
||
|
return false, probe.NewError(e)
|
||
10 years ago
|
}
|
||
|
|
||
9 years ago
|
// Signature version '4'.
|
||
|
canonicalRequest := s.getCanonicalRequest()
|
||
|
stringToSign := s.getStringToSign(canonicalRequest, t)
|
||
|
signingKey := s.getSigningKey(t)
|
||
|
newSignature := s.getSignature(signingKey, stringToSign)
|
||
|
|
||
|
// Verify if signature match.
|
||
|
if newSignature != signV4Values.Signature {
|
||
10 years ago
|
return false, nil
|
||
|
}
|
||
|
return true, nil
|
||
10 years ago
|
}
|