Ejemplo n.º 1
0
        public static AuthDataEntry SignedKeyAuthenticate(string stringToSign, string requestSignature, AuthenticationInformation authInfo)
        {
            AuthDataEntry authDataEntry;

            NephosAssertionException.Assert(!string.IsNullOrEmpty(stringToSign));
            NephosAssertionException.Assert(!string.IsNullOrEmpty(requestSignature));
            NephosAssertionException.Assert(authInfo != null);
            RequestContext      requestContext  = authInfo.RequestContext;
            NephosUriComponents uriComponents   = authInfo.UriComponents;
            NameValueCollection queryParameters = requestContext.QueryParameters;
            string item = queryParameters["sv"];

            byte[] sign = BlobSignedAccessHelper.ComputeUrlDecodedUtf8EncodedStringToSign(queryParameters, uriComponents);
            using (IEnumerator <AuthDataEntry> enumerator = SharedKeyAuthInfoHelper.GetSharedKeys(authInfo).GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    AuthDataEntry current  = enumerator.Current;
                    byte[]        numArray = SASUtilities.ComputeSignedKey(sign, current.AuthValue);
                    if (!SASUtilities.ComputeSignatureAndCompare((new UTF8Encoding()).GetBytes(stringToSign), numArray, requestSignature))
                    {
                        continue;
                    }
                    authDataEntry = current;
                    return(authDataEntry);
                }
                CultureInfo invariantCulture = CultureInfo.InvariantCulture;
                object[]    objArray         = new object[] { requestSignature, stringToSign };
                throw new AuthenticationFailureException(string.Format(invariantCulture, "The MAC signature found in the HTTP request '{0}' is not the same as any computed signature. Server used following string to sign: '{1}'.", objArray));
            }
            return(authDataEntry);
        }
Ejemplo n.º 2
0
        public override byte[] ComputeUrlDecodedUtf8EncodedStringToSign()
        {
            StringBuilder stringBuilder = new StringBuilder();

            if (base.SignedPermission.HasValue)
            {
                stringBuilder.Append(base.QueryParams["sp"]);
            }
            stringBuilder.Append("\n");
            if (base.SignedStart.HasValue)
            {
                stringBuilder.Append(base.QueryParams["st"]);
            }
            stringBuilder.Append("\n");
            if (base.SignedExpiry.HasValue)
            {
                stringBuilder.Append(base.QueryParams["se"]);
            }
            stringBuilder.Append("\n");
            stringBuilder.Append(BlobSignedAccessHelper.GetCanonicalizedResource(base.UriComponents, this.SignedResource, base.SignedVersion));
            stringBuilder.Append("\n");
            if (base.SignedIdentifier != null)
            {
                stringBuilder.Append(base.QueryParams["si"]);
            }
            if (base.SignedVersion != null)
            {
                if (VersioningHelper.CompareVersions(base.SignedVersion, "2015-04-05") >= 0)
                {
                    stringBuilder.Append("\n");
                    if (base.QueryParams["sip"] != null)
                    {
                        stringBuilder.Append(base.QueryParams["sip"]);
                    }
                    stringBuilder.Append("\n");
                    string item = base.QueryParams["spr"];
                    if (item != null)
                    {
                        stringBuilder.Append(item);
                    }
                }
                stringBuilder.Append("\n");
                stringBuilder.Append(base.QueryParams["sv"]);
                if (VersioningHelper.CompareVersions(base.SignedVersion, "2013-08-15") >= 0)
                {
                    stringBuilder.Append("\n");
                    if (base.QueryParams["rscc"] != null)
                    {
                        stringBuilder.Append(base.QueryParams["rscc"]);
                    }
                    stringBuilder.Append("\n");
                    if (base.QueryParams["rscd"] != null)
                    {
                        stringBuilder.Append(base.QueryParams["rscd"]);
                    }
                    stringBuilder.Append("\n");
                    if (base.QueryParams["rsce"] != null)
                    {
                        stringBuilder.Append(base.QueryParams["rsce"]);
                    }
                    stringBuilder.Append("\n");
                    if (base.QueryParams["rscl"] != null)
                    {
                        stringBuilder.Append(base.QueryParams["rscl"]);
                    }
                    stringBuilder.Append("\n");
                    if (base.QueryParams["rsct"] != null)
                    {
                        stringBuilder.Append(base.QueryParams["rsct"]);
                    }
                }
            }
            if (base.SignedExtraPermission.HasValue)
            {
                stringBuilder.Append("\n");
                stringBuilder.Append(base.QueryParams["sep"]);
            }
            return((new UTF8Encoding()).GetBytes(stringBuilder.ToString()));
        }
Ejemplo n.º 3
0
        public static string GenerateBlobSasUrl(string accountName, string containerName, string blobName, string blobSnapshot, IStorageAccount storageAccount, string requestUrlBase, bool includeWritePermission)
        {
            if (string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(containerName) || string.IsNullOrEmpty(blobName) || string.IsNullOrEmpty(requestUrlBase))
            {
                IStringDataEventStream error = Logger <IRestProtocolHeadLogger> .Instance.Error;
                object[] objArray            = new object[] { accountName, containerName, blobName, requestUrlBase };
                error.Log("Source blob account, container, blob name or requestUrl should not be empty. sourceUnversionedAccountName: {0} sourceUnversionedContainerName: {1} sourceBlobName: {2} requestUrlBase: {3}", objArray);
                return(string.Empty);
            }
            NameValueCollection nameValueCollection = new NameValueCollection();

            if (!includeWritePermission)
            {
                nameValueCollection.Add("sp", "r");
            }
            else
            {
                nameValueCollection.Add("sp", "rw");
            }
            nameValueCollection.Add("se", SASUtilities.EncodeTime(DateTime.MaxValue));
            nameValueCollection.Add("sv", "2016-02-19");
            nameValueCollection.Add("sr", "b");
            byte[] sign = BlobSignedAccessHelper.ComputeUrlDecodedUtf8EncodedStringToSign(nameValueCollection, new NephosUriComponents(accountName, containerName, HttpUtility.UrlDecode(blobName)));
            string str  = (new UTF8Encoding()).GetString(sign);

            str = str.Replace('\n', '.');
            SecretKeyV3 secretKeyV3 = null;

            if (secretKeyV3 == null)
            {
                Logger <IRestProtocolHeadLogger> .Instance.Error.Log("GenerateBlobSasUrl: could not find a system key for the account");

                return(string.Empty);
            }
            string str1 = BlobSignedAccessHelper.ComputeHMACSHA256(secretKeyV3.Value, sign);

            if (string.IsNullOrEmpty(str1))
            {
                Logger <IRestProtocolHeadLogger> .Instance.Error.Log("GenerateBlobSasUrl: could not get HMACSHA256");

                return(string.Empty);
            }
            nameValueCollection.Add("sig", str1);
            if (!string.IsNullOrEmpty(blobSnapshot))
            {
                nameValueCollection.Add("snapshot", blobSnapshot);
            }
            UriBuilder    uriBuilder    = new UriBuilder(requestUrlBase);
            StringBuilder stringBuilder = new StringBuilder();

            string[] allKeys = nameValueCollection.AllKeys;
            for (int i = 0; i < (int)allKeys.Length; i++)
            {
                string str2 = allKeys[i];
                stringBuilder.Append(HttpUtilities.PathEncode(str2));
                stringBuilder.Append("=");
                stringBuilder.Append(HttpUtilities.PathEncode(nameValueCollection[str2]));
                stringBuilder.Append("&");
            }
            if (stringBuilder.Length > 0)
            {
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
            }
            uriBuilder.Query = stringBuilder.ToString();
            return(uriBuilder.ToString());
        }
Ejemplo n.º 4
0
        public static byte[] ComputeUrlDecodedUtf8EncodedStringToSign(NameValueCollection queryParams, NephosUriComponents uriComponents)
        {
            string        item          = queryParams["st"];
            string        str           = queryParams["se"];
            string        item1         = queryParams["sp"];
            string        str1          = queryParams["sr"];
            string        item2         = queryParams["si"];
            string        str2          = queryParams["sip"];
            string        item3         = queryParams["spr"];
            string        str3          = queryParams["sv"];
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(item1 ?? string.Empty);
            stringBuilder.Append("\n");
            stringBuilder.Append(item ?? string.Empty);
            stringBuilder.Append("\n");
            stringBuilder.Append(str ?? string.Empty);
            stringBuilder.Append("\n");
            stringBuilder.Append(BlobSignedAccessHelper.GetCanonicalizedResource(uriComponents, SASUtilities.ParseSasAccessLevel(str1), str3));
            stringBuilder.Append("\n");
            stringBuilder.Append(item2 ?? string.Empty);
            if (str3 != null)
            {
                if (VersioningHelper.CompareVersions(str3, "2015-04-05") >= 0)
                {
                    stringBuilder.Append("\n");
                    stringBuilder.Append(str2 ?? string.Empty);
                    stringBuilder.Append("\n");
                    stringBuilder.Append(item3 ?? string.Empty);
                }
                stringBuilder.Append("\n");
                stringBuilder.Append(queryParams["sv"]);
                if (VersioningHelper.CompareVersions(str3, "2014-02-14") >= 0)
                {
                    stringBuilder.Append("\n");
                    if (queryParams["rscc"] != null)
                    {
                        stringBuilder.Append(queryParams["rscc"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rscd"] != null)
                    {
                        stringBuilder.Append(queryParams["rscd"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rsce"] != null)
                    {
                        stringBuilder.Append(queryParams["rsce"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rscl"] != null)
                    {
                        stringBuilder.Append(queryParams["rscl"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rsct"] != null)
                    {
                        stringBuilder.Append(queryParams["rsct"]);
                    }
                }
            }
            if (queryParams["sep"] != null)
            {
                stringBuilder.Append("\n");
                stringBuilder.Append(queryParams["sep"]);
            }
            return((new UTF8Encoding()).GetBytes(stringBuilder.ToString()));
        }
Ejemplo n.º 5
0
        private IEnumerator <IAsyncResult> AuthenticateImpl(IStorageAccount storageAccount, RequestContext requestContext, NephosUriComponents uriComponents, AuthenticationManager.GetStringToSignCallback getStringToSignCallback, TimeSpan timeout, AsyncIteratorContext <IAuthenticationResult> context)
        {
            bool flag;
            SignedAccessHelper   blobSignedAccessHelper;
            IStorageAccount      operationStatus;
            ContainerAclSettings containerAclSetting;
            Duration             startingNow     = Duration.StartingNow;
            NameValueCollection  queryParameters = requestContext.QueryParameters;

            if (AuthenticationManager.IsInvalidAccess(requestContext))
            {
                throw new InvalidAuthenticationInfoException("Ambiguous authentication scheme credentials providedRequest contains authentication credentials for signed access and authenticated access");
            }
            bool flag1 = AuthenticationManager.IsAuthenticatedAccess(requestContext);
            bool flag2 = AuthenticationManager.IsSignatureAccess(requestContext);

            flag = (!flag1 ? false : AuthenticationManager.IsAuthenticatedAccess(requestContext, "SignedKey"));
            bool flag3 = flag;
            bool flag4 = (flag1 ? false : !flag2);
            bool flag5 = string.IsNullOrEmpty(requestContext.RequestHeaderRestVersion);

            if (this.DenyUnversionedAuthenticatedAccess && flag5 && flag1)
            {
                throw new AuthenticationFailureException(string.Format(CultureInfo.InvariantCulture, "Unversioned authenticated access is not allowed.", new object[0]));
            }
            if ((!flag1 || flag3) && !flag4)
            {
                NephosAssertionException.Assert((flag2 ? true : flag3));
                bool flag6 = (flag2 ? false : flag3);
                if (!AuthenticationManager.IsAccountSasAccess(requestContext.QueryParameters))
                {
                    blobSignedAccessHelper = new BlobSignedAccessHelper(requestContext, uriComponents);
                }
                else
                {
                    if (flag6)
                    {
                        throw new AuthenticationFailureException("SignedKey is not supported with account-level SAS.");
                    }
                    blobSignedAccessHelper = new AccountSasHelper(requestContext, uriComponents);
                }
                blobSignedAccessHelper.ParseAccessPolicyFields(flag6);
                blobSignedAccessHelper.PerformSignedAccessAuthenticationFirstPhaseValidations();
                AccountIdentifier signedAccessAccountIdentifier = null;
                if (!flag6)
                {
                    byte[] sign = blobSignedAccessHelper.ComputeUrlDecodedUtf8EncodedStringToSign();
                    if (storageAccount == null || !string.Equals(storageAccount.Name, uriComponents.AccountName))
                    {
                        try
                        {
                            operationStatus = this.storageManager.CreateAccountInstance(uriComponents.AccountName);
                            if (requestContext != null)
                            {
                                operationStatus.OperationStatus = requestContext.OperationStatus;
                            }
                        }
                        catch (ArgumentOutOfRangeException argumentOutOfRangeException)
                        {
                            throw new AuthenticationFailureException(string.Format(CultureInfo.InvariantCulture, "The account name is invalid.", new object[0]));
                        }
                        operationStatus.Timeout = startingNow.Remaining(timeout);
                        IAsyncResult asyncResult = operationStatus.BeginGetProperties(AccountPropertyNames.All, null, context.GetResumeCallback(), context.GetResumeState("XFEBlobAuthenticationManager.AuthenticateImpl"));
                        yield return(asyncResult);

                        try
                        {
                            operationStatus.EndGetProperties(asyncResult);
                        }
                        catch (AccountNotFoundException accountNotFoundException1)
                        {
                            AccountNotFoundException accountNotFoundException = accountNotFoundException1;
                            CultureInfo invariantCulture = CultureInfo.InvariantCulture;
                            object[]    name             = new object[] { operationStatus.Name };
                            throw new AuthenticationFailureException(string.Format(invariantCulture, "Cannot find the claimed account when trying to GetProperties for the account {0}.", name), accountNotFoundException);
                        }
                        catch (Exception exception1)
                        {
                            Exception exception            = exception1;
                            IStringDataEventStream warning = Logger <IRestProtocolHeadLogger> .Instance.Warning;
                            object[] objArray = new object[] { operationStatus.Name, exception };
                            warning.Log("Rethrow exception when trying to GetProperties for the account {0}: {1}", objArray);
                            throw;
                        }
                    }
                    else
                    {
                        operationStatus = storageAccount;
                    }
                    if (!blobSignedAccessHelper.ComputeSignatureAndCompare(sign, operationStatus.SecretKeysV3))
                    {
                        throw new AuthenticationFailureException(string.Concat("Signature did not match. String to sign used was ", (new UTF8Encoding()).GetString(sign)));
                    }
                    NephosAssertionException.Assert(blobSignedAccessHelper.KeyUsedForSigning != null, "Key used for signing cannot be null");
                    signedAccessAccountIdentifier = blobSignedAccessHelper.CreateAccountIdentifier(operationStatus);
                    if (storageAccount != operationStatus)
                    {
                        operationStatus.Dispose();
                    }
                }
                else
                {
                    IAsyncResult asyncResult1 = this.nephosAuthenticationManager.BeginAuthenticate(storageAccount, requestContext, uriComponents, getStringToSignCallback, startingNow.Remaining(timeout), context.GetResumeCallback(), context.GetResumeState("XFEBlobAuthenticationManager.AuthenticateImpl"));
                    yield return(asyncResult1);

                    IAuthenticationResult authenticationResult = this.nephosAuthenticationManager.EndAuthenticate(asyncResult1);
                    signedAccessAccountIdentifier = new SignedAccessAccountIdentifier(authenticationResult.AccountIdentifier);
                }
                if (blobSignedAccessHelper.IsRevocableAccess)
                {
                    using (IBlobContainer blobContainer = this.storageManager.CreateBlobContainerInstance(uriComponents.AccountName, uriComponents.ContainerName))
                    {
                        ContainerPropertyNames containerPropertyName = ContainerPropertyNames.ServiceMetadata;
                        if (requestContext != null)
                        {
                            blobContainer.OperationStatus = requestContext.OperationStatus;
                        }
                        blobContainer.Timeout = startingNow.Remaining(timeout);
                        IAsyncResult asyncResult2 = blobContainer.BeginGetProperties(containerPropertyName, null, context.GetResumeCallback(), context.GetResumeState("XFEBlobAuthenticationManager.AuthenticateImpl"));
                        yield return(asyncResult2);

                        try
                        {
                            blobContainer.EndGetProperties(asyncResult2);
                        }
                        catch (Exception exception3)
                        {
                            Exception exception2 = exception3;
                            if (exception2 is ContainerNotFoundException)
                            {
                                throw new AuthenticationFailureException("Error locating SAS identifier", exception2);
                            }
                            IStringDataEventStream stringDataEventStream = Logger <IRestProtocolHeadLogger> .Instance.Warning;
                            object[] accountName = new object[] { uriComponents.AccountName, uriComponents.ContainerName, exception2 };
                            stringDataEventStream.Log("Rethrow exception when trying to fetch SAS identifier account {0} container {1} : {2}", accountName);
                            throw;
                        }
                        try
                        {
                            containerAclSetting = new ContainerAclSettings(blobContainer.ServiceMetadata);
                        }
                        catch (MetadataFormatException metadataFormatException1)
                        {
                            MetadataFormatException metadataFormatException = metadataFormatException1;
                            throw new NephosStorageDataCorruptionException(string.Format("Error decoding Acl setting for container {0}", uriComponents.ContainerName), metadataFormatException);
                        }
                    }
                    try
                    {
                        blobSignedAccessHelper.ValidateAndDeriveEffectiveAccessPolicy(blobSignedAccessHelper.LocateSasIdentifier(containerAclSetting.SASIdentifiers));
                        blobSignedAccessHelper.PerformSignedAccessAuthenticationSecondPhaseValidations();
                        signedAccessAccountIdentifier.Initialize(blobSignedAccessHelper);
                        context.ResultData = new AuthenticationResult(signedAccessAccountIdentifier, blobSignedAccessHelper.SignedVersion, true);
                    }
                    catch (FormatException formatException)
                    {
                        throw new AuthenticationFailureException("Signature fields not well formed.", formatException);
                    }
                }
                else
                {
                    signedAccessAccountIdentifier.Initialize(blobSignedAccessHelper);
                    context.ResultData = new AuthenticationResult(signedAccessAccountIdentifier, blobSignedAccessHelper.SignedVersion, true);
                }
            }
            else
            {
                IAsyncResult asyncResult3 = this.nephosAuthenticationManager.BeginAuthenticate(storageAccount, requestContext, uriComponents, getStringToSignCallback, startingNow.Remaining(timeout), context.GetResumeCallback(), context.GetResumeState("XFEBlobAuthenticationManager.AuthenticateImpl"));
                yield return(asyncResult3);

                context.ResultData = this.nephosAuthenticationManager.EndAuthenticate(asyncResult3);
            }
        }