parent
312af12fd5
commit
7fea9cb550
@ -0,0 +1,139 @@ |
||||
/* |
||||
* Minio Cloud Storage, (C) 2015 Minio, Inc. |
||||
* |
||||
* 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. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"crypto/hmac" |
||||
"encoding/hex" |
||||
"io" |
||||
"regexp" |
||||
"strings" |
||||
"unicode/utf8" |
||||
|
||||
"github.com/minio/minio/pkg/crypto/sha256" |
||||
) |
||||
|
||||
///
|
||||
/// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
|
||||
///
|
||||
/// User-Agent:
|
||||
///
|
||||
/// This is ignored from signing because signing this causes problems with generating pre-signed URLs
|
||||
/// (that are executed by other agents) or when customers pass requests through proxies, which may
|
||||
/// modify the user-agent.
|
||||
///
|
||||
/// Content-Length:
|
||||
///
|
||||
/// This is ignored from signing because generating a pre-signed URL should not provide a content-length
|
||||
/// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
|
||||
/// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
|
||||
/// implicitly validates the payload length (since changing the number of bytes would change the checksum)
|
||||
/// and therefore this header is not valuable in the signature.
|
||||
///
|
||||
/// Content-Type:
|
||||
///
|
||||
/// Signing this header causes quite a number of problems in browser environments, where browsers
|
||||
/// like to modify and normalize the content-type header in different ways. There is more information
|
||||
/// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
|
||||
/// and reduces the possibility of future bugs
|
||||
///
|
||||
/// Authorization:
|
||||
///
|
||||
/// Is skipped for obvious reasons
|
||||
///
|
||||
var ignoredHeaders = map[string]bool{ |
||||
"Authorization": true, |
||||
"Content-Type": true, |
||||
"Content-Length": true, |
||||
"User-Agent": true, |
||||
} |
||||
|
||||
// sum256Reader calculate sha256 sum for an input read seeker
|
||||
func sum256Reader(reader io.ReadSeeker) ([]byte, error) { |
||||
h := sha256.New() |
||||
var err error |
||||
|
||||
start, _ := reader.Seek(0, 1) |
||||
defer reader.Seek(start, 0) |
||||
|
||||
for err == nil { |
||||
length := 0 |
||||
byteBuffer := make([]byte, 1024*1024) |
||||
length, err = reader.Read(byteBuffer) |
||||
byteBuffer = byteBuffer[0:length] |
||||
h.Write(byteBuffer) |
||||
} |
||||
|
||||
if err != io.EOF { |
||||
return nil, err |
||||
} |
||||
|
||||
return h.Sum(nil), nil |
||||
} |
||||
|
||||
// sum256 calculate sha256 sum for an input byte array
|
||||
func sum256(data []byte) []byte { |
||||
hash := sha256.New() |
||||
hash.Write(data) |
||||
return hash.Sum(nil) |
||||
} |
||||
|
||||
// sumHMAC calculate hmac between two input byte array
|
||||
func sumHMAC(key []byte, data []byte) []byte { |
||||
hash := hmac.New(sha256.New, key) |
||||
hash.Write(data) |
||||
return hash.Sum(nil) |
||||
} |
||||
|
||||
// getURLEncodedName encode the strings from UTF-8 byte representations to HTML hex escape sequences
|
||||
//
|
||||
// This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
|
||||
// non english characters cannot be parsed due to the nature in which url.Encode() is written
|
||||
//
|
||||
// This function on the other hand is a direct replacement for url.Encode() technique to support
|
||||
// pretty much every UTF-8 character.
|
||||
func getURLEncodedName(name string) string { |
||||
// if object matches reserved string, no need to encode them
|
||||
reservedNames := regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$") |
||||
if reservedNames.MatchString(name) { |
||||
return name |
||||
} |
||||
var encodedName string |
||||
for _, s := range name { |
||||
if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
|
||||
encodedName = encodedName + string(s) |
||||
continue |
||||
} |
||||
switch s { |
||||
case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
|
||||
encodedName = encodedName + string(s) |
||||
continue |
||||
default: |
||||
len := utf8.RuneLen(s) |
||||
if len < 0 { |
||||
return name |
||||
} |
||||
u := make([]byte, len) |
||||
utf8.EncodeRune(u, s) |
||||
for _, r := range u { |
||||
hex := hex.EncodeToString([]byte{r}) |
||||
encodedName = encodedName + "%" + strings.ToUpper(hex) |
||||
} |
||||
} |
||||
} |
||||
return encodedName |
||||
} |
@ -0,0 +1,243 @@ |
||||
/* |
||||
* Minio Cloud Storage, (C) 2015 Minio, Inc. |
||||
* |
||||
* 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. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"bytes" |
||||
"encoding/hex" |
||||
"io" |
||||
"net/http" |
||||
"sort" |
||||
"strings" |
||||
"time" |
||||
|
||||
"github.com/minio/minio/pkg/crypto/sha256" |
||||
"github.com/minio/minio/pkg/probe" |
||||
) |
||||
|
||||
type rpcSignatureHandler struct { |
||||
handler http.Handler |
||||
} |
||||
|
||||
// RPCSignatureHandler to validate authorization header for the incoming request.
|
||||
func RPCSignatureHandler(h http.Handler) http.Handler { |
||||
return signatureHandler{h} |
||||
} |
||||
|
||||
type rpcSignature struct { |
||||
AccessKeyID string |
||||
SecretAccessKey string |
||||
Signature string |
||||
SignedHeaders []string |
||||
Request *http.Request |
||||
} |
||||
|
||||
// getCanonicalHeaders generate a list of request headers with their values
|
||||
func (r *rpcSignature) getCanonicalHeaders(signedHeaders map[string][]string) string { |
||||
var headers []string |
||||
vals := make(map[string][]string) |
||||
for k, vv := range signedHeaders { |
||||
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": |
||||
buf.WriteString(r.Request.Host) |
||||
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
|
||||
func (r *rpcSignature) getSignedHeaders(signedHeaders map[string][]string) string { |
||||
var headers []string |
||||
for k := range signedHeaders { |
||||
headers = append(headers, strings.ToLower(k)) |
||||
} |
||||
headers = append(headers, "host") |
||||
sort.Strings(headers) |
||||
return strings.Join(headers, ";") |
||||
} |
||||
|
||||
// extractSignedHeaders extract signed headers from Authorization header
|
||||
func (r rpcSignature) extractSignedHeaders() map[string][]string { |
||||
extractedSignedHeadersMap := make(map[string][]string) |
||||
for _, header := range r.SignedHeaders { |
||||
val, ok := r.Request.Header[http.CanonicalHeaderKey(header)] |
||||
if !ok { |
||||
// if not found continue, we will fail later
|
||||
continue |
||||
} |
||||
extractedSignedHeadersMap[header] = val |
||||
} |
||||
return extractedSignedHeadersMap |
||||
} |
||||
|
||||
// getCanonicalRequest generate a canonical request of style
|
||||
//
|
||||
// canonicalRequest =
|
||||
// <HTTPMethod>\n
|
||||
// <CanonicalURI>\n
|
||||
// <CanonicalQueryString>\n
|
||||
// <CanonicalHeaders>\n
|
||||
// <SignedHeaders>\n
|
||||
// <HashedPayload>
|
||||
//
|
||||
func (r *rpcSignature) getCanonicalRequest() string { |
||||
payload := r.Request.Header.Get(http.CanonicalHeaderKey("x-amz-content-sha256")) |
||||
r.Request.URL.RawQuery = strings.Replace(r.Request.URL.Query().Encode(), "+", "%20", -1) |
||||
encodedPath := getURLEncodedName(r.Request.URL.Path) |
||||
// convert any space strings back to "+"
|
||||
encodedPath = strings.Replace(encodedPath, "+", "%20", -1) |
||||
canonicalRequest := strings.Join([]string{ |
||||
r.Request.Method, |
||||
encodedPath, |
||||
r.Request.URL.RawQuery, |
||||
r.getCanonicalHeaders(r.extractSignedHeaders()), |
||||
r.getSignedHeaders(r.extractSignedHeaders()), |
||||
payload, |
||||
}, "\n") |
||||
return canonicalRequest |
||||
} |
||||
|
||||
// getScope generate a string of a specific date, an AWS region, and a service
|
||||
func (r rpcSignature) getScope(t time.Time) string { |
||||
scope := strings.Join([]string{ |
||||
t.Format(yyyymmdd), |
||||
"milkyway", |
||||
"rpc", |
||||
"rpc_request", |
||||
}, "/") |
||||
return scope |
||||
} |
||||
|
||||
// getStringToSign a string based on selected query values
|
||||
func (r rpcSignature) getStringToSign(canonicalRequest string, t time.Time) string { |
||||
stringToSign := authHeaderPrefix + "\n" + t.Format(iso8601Format) + "\n" |
||||
stringToSign = stringToSign + r.getScope(t) + "\n" |
||||
stringToSign = stringToSign + hex.EncodeToString(sha256.Sum256([]byte(canonicalRequest))) |
||||
return stringToSign |
||||
} |
||||
|
||||
// getSigningKey hmac seed to calculate final signature
|
||||
func (r rpcSignature) getSigningKey(t time.Time) []byte { |
||||
secret := r.SecretAccessKey |
||||
date := sumHMAC([]byte("MINIO"+secret), []byte(t.Format(yyyymmdd))) |
||||
region := sumHMAC(date, []byte("milkyway")) |
||||
service := sumHMAC(region, []byte("rpc")) |
||||
signingKey := sumHMAC(service, []byte("rpc_request")) |
||||
return signingKey |
||||
} |
||||
|
||||
// getSignature final signature in hexadecimal form
|
||||
func (r rpcSignature) getSignature(signingKey []byte, stringToSign string) string { |
||||
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign))) |
||||
} |
||||
|
||||
func (r rpcSignature) DoesSignatureMatch(hashedPayload string) (bool, *probe.Error) { |
||||
// set new calulated payload
|
||||
r.Request.Header.Set("X-Minio-Content-Sha256", hashedPayload) |
||||
|
||||
// Add date if not present throw error
|
||||
var date string |
||||
if date = r.Request.Header.Get(http.CanonicalHeaderKey("x-minio-date")); date == "" { |
||||
if date = r.Request.Header.Get("Date"); date == "" { |
||||
return false, probe.NewError(errMissingDateHeader) |
||||
} |
||||
} |
||||
t, err := time.Parse(iso8601Format, date) |
||||
if err != nil { |
||||
return false, probe.NewError(err) |
||||
} |
||||
canonicalRequest := r.getCanonicalRequest() |
||||
stringToSign := r.getStringToSign(canonicalRequest, t) |
||||
signingKey := r.getSigningKey(t) |
||||
newSignature := r.getSignature(signingKey, stringToSign) |
||||
|
||||
if newSignature != r.Signature { |
||||
return false, nil |
||||
} |
||||
return true, nil |
||||
} |
||||
|
||||
func isRequestSignatureRPC(req *http.Request) bool { |
||||
if _, ok := req.Header["Authorization"]; ok { |
||||
return ok |
||||
} |
||||
return false |
||||
} |
||||
|
||||
func (s rpcSignatureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
||||
var signature *rpcSignature |
||||
if isRequestSignatureRPC(r) { |
||||
// Init signature V4 verification
|
||||
var err *probe.Error |
||||
signature, err = initSignatureRPC(r) |
||||
if err != nil { |
||||
switch err.ToGoError() { |
||||
case errInvalidRegion: |
||||
errorIf(err.Trace(), "Unknown region in authorization header.", nil) |
||||
writeErrorResponse(w, r, AuthorizationHeaderMalformed, r.URL.Path) |
||||
return |
||||
case errAccessKeyIDInvalid: |
||||
errorIf(err.Trace(), "Invalid access key id.", nil) |
||||
writeErrorResponse(w, r, InvalidAccessKeyID, r.URL.Path) |
||||
return |
||||
default: |
||||
errorIf(err.Trace(), "Initializing signature v4 failed.", nil) |
||||
writeErrorResponse(w, r, InternalError, r.URL.Path) |
||||
return |
||||
} |
||||
} |
||||
buffer := new(bytes.Buffer) |
||||
if _, err := io.Copy(buffer, r.Body); err != nil { |
||||
errorIf(probe.NewError(err), "Unable to read payload from request body.", nil) |
||||
writeErrorResponse(w, r, InternalError, r.URL.Path) |
||||
return |
||||
} |
||||
value := sha256.Sum256(buffer.Bytes()) |
||||
ok, err := signature.DoesSignatureMatch(hex.EncodeToString(value[:])) |
||||
if err != nil { |
||||
errorIf(err.Trace(), "Unable to verify signature.", nil) |
||||
writeErrorResponse(w, r, InternalError, r.URL.Path) |
||||
return |
||||
} |
||||
if !ok { |
||||
writeErrorResponse(w, r, SignatureDoesNotMatch, r.URL.Path) |
||||
return |
||||
} |
||||
s.handler.ServeHTTP(w, r) |
||||
return |
||||
} |
||||
writeErrorResponse(w, r, AccessDenied, r.URL.Path) |
||||
} |
@ -0,0 +1,123 @@ |
||||
/* |
||||
* Minio Cloud Storage, (C) 2015 Minio, Inc. |
||||
* |
||||
* 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. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"net/http" |
||||
"strings" |
||||
|
||||
"github.com/minio/minio/pkg/probe" |
||||
) |
||||
|
||||
const ( |
||||
rpcAuthHeaderPrefix = "MINIORPC" |
||||
) |
||||
|
||||
// getRPCCredentialsFromAuth parse credentials tag from authorization value
|
||||
// Authorization:
|
||||
// Authorization: MINIORPC Credential=admin/20130524/milkyway/rpc/rpc_request,
|
||||
// SignedHeaders=host;x-minio-date, Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024
|
||||
func getRPCCredentialsFromAuth(authValue string) ([]string, *probe.Error) { |
||||
if authValue == "" { |
||||
return nil, probe.NewError(errMissingAuthHeaderValue) |
||||
} |
||||
authFields := strings.Split(strings.TrimSpace(authValue), ",") |
||||
if len(authFields) != 3 { |
||||
return nil, probe.NewError(errInvalidAuthHeaderValue) |
||||
} |
||||
authPrefixFields := strings.Fields(authFields[0]) |
||||
if len(authPrefixFields) != 2 { |
||||
return nil, probe.NewError(errMissingFieldsAuthHeader) |
||||
} |
||||
if authPrefixFields[0] != rpcAuthHeaderPrefix { |
||||
return nil, probe.NewError(errInvalidAuthHeaderPrefix) |
||||
} |
||||
credentials := strings.Split(strings.TrimSpace(authPrefixFields[1]), "=") |
||||
if len(credentials) != 2 { |
||||
return nil, probe.NewError(errMissingFieldsCredentialTag) |
||||
} |
||||
if len(strings.Split(strings.TrimSpace(authFields[1]), "=")) != 2 { |
||||
return nil, probe.NewError(errMissingFieldsSignedHeadersTag) |
||||
} |
||||
if len(strings.Split(strings.TrimSpace(authFields[2]), "=")) != 2 { |
||||
return nil, probe.NewError(errMissingFieldsSignatureTag) |
||||
} |
||||
credentialElements := strings.Split(strings.TrimSpace(credentials[1]), "/") |
||||
if len(credentialElements) != 5 { |
||||
return nil, probe.NewError(errCredentialTagMalformed) |
||||
} |
||||
return credentialElements, nil |
||||
} |
||||
|
||||
// verify if rpcAuthHeader value has valid region
|
||||
func isValidRPCRegion(authHeaderValue string) *probe.Error { |
||||
credentialElements, err := getRPCCredentialsFromAuth(authHeaderValue) |
||||
if err != nil { |
||||
return err.Trace() |
||||
} |
||||
region := credentialElements[2] |
||||
if region != "milkyway" { |
||||
return probe.NewError(errInvalidRegion) |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// stripRPCAccessKeyID - strip only access key id from auth header
|
||||
func stripRPCAccessKeyID(authHeaderValue string) (string, *probe.Error) { |
||||
if err := isValidRegion(authHeaderValue); err != nil { |
||||
return "", err.Trace() |
||||
} |
||||
credentialElements, err := getRPCCredentialsFromAuth(authHeaderValue) |
||||
if err != nil { |
||||
return "", err.Trace() |
||||
} |
||||
accessKeyID := credentialElements[0] |
||||
if !IsValidAccessKey(accessKeyID) { |
||||
return "", probe.NewError(errAccessKeyIDInvalid) |
||||
} |
||||
return accessKeyID, nil |
||||
} |
||||
|
||||
// initSignatureRPC initializing rpc signature verification
|
||||
func initSignatureRPC(req *http.Request) (*rpcSignature, *probe.Error) { |
||||
// strip auth from authorization header
|
||||
authHeaderValue := req.Header.Get("Authorization") |
||||
accessKeyID, err := stripAccessKeyID(authHeaderValue) |
||||
if err != nil { |
||||
return nil, err.Trace() |
||||
} |
||||
authConfig, err := LoadConfig() |
||||
if err != nil { |
||||
return nil, err.Trace() |
||||
} |
||||
authFields := strings.Split(strings.TrimSpace(authHeaderValue), ",") |
||||
signedHeaders := strings.Split(strings.Split(strings.TrimSpace(authFields[1]), "=")[1], ";") |
||||
signature := strings.Split(strings.TrimSpace(authFields[2]), "=")[1] |
||||
for _, user := range authConfig.Users { |
||||
if user.AccessKeyID == accessKeyID { |
||||
signature := &rpcSignature{ |
||||
AccessKeyID: user.AccessKeyID, |
||||
SecretAccessKey: user.SecretAccessKey, |
||||
Signature: signature, |
||||
SignedHeaders: signedHeaders, |
||||
Request: req, |
||||
} |
||||
return signature, nil |
||||
} |
||||
} |
||||
return nil, probe.NewError(errAccessKeyIDInvalid) |
||||
} |
Loading…
Reference in new issue