Beispiel #1
0
        public static ConditionInformation GetConditionInfoFromRequest(NameValueCollection requestHeaders, OperationTypeForConditionParsing operationType, string requestVersion)
        {
            ConditionalHeaders conditionalHeadersFromRequest = ConditionExtractor.GetConditionalHeadersFromRequest(requestHeaders);

            if (conditionalHeadersFromRequest == null)
            {
                return(null);
            }
            if (operationType == OperationTypeForConditionParsing.ReadOperation || operationType == OperationTypeForConditionParsing.WriteOperation)
            {
                return(ConditionExtractor.ExecuteExtractors(conditionalHeadersFromRequest, requestHeaders, operationType, requestVersion, ConditionExtractor.extractors));
            }
            NephosAssertionException.Assert(operationType == OperationTypeForConditionParsing.CopyOperation);
            ConditionInformation copySourceIfModifiedSince = ConditionExtractor.ExecuteExtractors(conditionalHeadersFromRequest, requestHeaders, operationType, requestVersion, ConditionExtractor.extractors);
            ConditionInformation conditionInformation      = ConditionExtractor.ExecuteExtractors(conditionalHeadersFromRequest, requestHeaders, operationType, requestVersion, ConditionExtractor.copySourceExtractors);

            if (copySourceIfModifiedSince == null)
            {
                return(conditionInformation);
            }
            if (conditionInformation != null)
            {
                copySourceIfModifiedSince.CopySourceIfModifiedSince    = conditionInformation.CopySourceIfModifiedSince;
                copySourceIfModifiedSince.CopySourceIfNotModifiedSince = conditionInformation.CopySourceIfNotModifiedSince;
                copySourceIfModifiedSince.CopySourceIfMatch            = conditionInformation.CopySourceIfMatch;
                copySourceIfModifiedSince.CopySourceIfNoneMatch        = conditionInformation.CopySourceIfNoneMatch;
                NephosAssertionException.Assert(copySourceIfModifiedSince.ConditionFailStatusCode == conditionInformation.ConditionFailStatusCode);
            }
            return(copySourceIfModifiedSince);
        }
Beispiel #2
0
        private IEnumerator <IAsyncResult> ReadImpl(byte[] buffer, int offset, int count, AsyncIteratorContext <int> context)
        {
            IAsyncResult asyncResult = null;

            this.CheckDisposed();
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("The number of bytes to read cannot be negative", "count");
            }
            this.readTimer.Start();
            if (count > 0)
            {
                asyncResult = this.innerStream.BeginRead(buffer, offset, count, context.GetResumeCallback(), context.GetResumeState("TallyKeepingStream.ReadImpl"));
                yield return(asyncResult);
            }
            int num = 0;

            if (count > 0)
            {
                NephosAssertionException.Assert(asyncResult != null);
                num = this.innerStream.EndRead(asyncResult);
            }
            this.readTimer.Stop();
            if (num > 0 && this.readingEvent != null)
            {
                this.RecordPreOperationDataCount((long)num);
                this.readingEvent(this, this.EventArgs);
            }
            this.UpdateBytesRead((long)num);
            context.ResultData = num;
        }
Beispiel #3
0
        internal static HttpProcessorConfiguration LoadHttpProcessorConfiguration(IServiceEntrySink sink, string hostSuffixesConfigParamName, string enableStorageDomainNamesConfigParamName)
        {
            HttpProcessorConfiguration httpProcessorConfiguration = new HttpProcessorConfiguration()
            {
                AllowPathStyleUris         = ConfigurationHelper.GetConfigSetting <bool>(sink, "NephosAllowPathStyleUris", "Allow path-style URIs"),
                ValidHostSuffixes          = ConfigurationHelper.GetHostSuffixes(sink, hostSuffixesConfigParamName),
                MaskClientIPAddressesInLog = ConfigurationHelper.GetIPAddressMaskSetting(sink)
            };

            if (!httpProcessorConfiguration.AllowPathStyleUris)
            {
                NephosAssertionException.Assert(httpProcessorConfiguration.ValidHostSuffixes != null, "Host suffixes can't be null when AllowPathStyleUris is false. Check service model configuaration.");
                NephosAssertionException.Assert((int)httpProcessorConfiguration.ValidHostSuffixes.Length > 0, "Host suffixes can't be empty when AllowPathStyleUris is false. Check service model configuaration.");
            }
            httpProcessorConfiguration.ValidHostSuffixes = httpProcessorConfiguration.ValidHostSuffixes ?? new string[0];
            httpProcessorConfiguration.IncludeInternalDetailsInErrorResponses = ConfigurationHelper.GetConfigSetting <bool>(sink, "NephosIncludeInternalDetailsInErrorResponses", "Include internal details in error responses");
            if (!string.IsNullOrEmpty(enableStorageDomainNamesConfigParamName))
            {
                httpProcessorConfiguration.EnableStorageDomainNames = ConfigurationHelper.GetConfigSetting <bool>(sink, enableStorageDomainNamesConfigParamName, "Enable storage domain names");
            }
            try
            {
                httpProcessorConfiguration.StampName = ConfigurationHelper.GetConfigSetting <string>(sink, "StampName", "Stamp Name");
            }
            catch (Exception exception1)
            {
                Exception exception          = exception1;
                IStringDataEventStream error = Logger <IRestProtocolHeadLogger> .Instance.Error;
                object[] str = new object[] { exception.ToString() };
                error.Log("Hit Exception while reading StampName setting from ACS: {0}", str);
            }
            return(httpProcessorConfiguration);
        }
Beispiel #4
0
        public NephosErrorDetails(NephosStatusEntry statusEntry, MeasurementEventStatus eventStatus, Exception exception, string userSafeErrorMessage, NameValueCollection headers, NameValueCollection additionalDetails, byte[] errorResponse, bool isFatal, bool hasErrorResponse, bool skipBillingAndMetrics)
        {
            NephosAssertionException.Assert(statusEntry != null, "statusEntry can't be null.");
            NephosAssertionException.Assert(true, "eventStatus can't be null.");
            this.StatusEntry           = statusEntry;
            this.EventStatus           = eventStatus;
            this.ErrorException        = exception;
            this.ResponseHeaders       = headers;
            this.AdditionalDetails     = additionalDetails;
            this.ErrorResponse         = errorResponse;
            this.IsFatal               = isFatal;
            this.HasErrorResponse      = hasErrorResponse;
            this.SkipBillingAndMetrics = skipBillingAndMetrics;
            StringBuilder stringBuilder = new StringBuilder(statusEntry.UserMessage);

            if (!string.IsNullOrEmpty(userSafeErrorMessage))
            {
                stringBuilder.AppendFormat(" Additional detail: {0}", userSafeErrorMessage);
            }
            Guid activityId = Trace.ActivityId;

            if (activityId != Guid.Empty)
            {
                string   str    = activityId.ToString("D");
                DateTime utcNow = DateTime.UtcNow;
                stringBuilder.AppendFormat("\nRequestId:{0}\nTime:{1}", str, utcNow.ToString("o"));
            }
            this.UserSafeErrorMessage = stringBuilder.ToString();
        }
Beispiel #5
0
        private IEnumerator <IAsyncResult> SnapshotBlobImpl(byte[] metadata, IBlobObjectCondition condition, AsyncIteratorContext <DateTime> context)
        {
            IAsyncResult asyncResult;

            try
            {
                asyncResult = this.blob.BeginSnapshotBlob(metadata, Helpers.Convert(condition), context.GetResumeCallback(), context.GetResumeState("BaseBlobObject.SnapshotBlobImpl"));
            }
            catch (Exception exception)
            {
                StorageStamp.TranslateException(exception);
                throw;
            }
            yield return(asyncResult);

            DateTime minValue = DateTime.MinValue;

            try
            {
                minValue = this.blob.EndSnapshotBlob(asyncResult);
            }
            catch (Exception exception1)
            {
                StorageStamp.TranslateException(exception1);
                throw;
            }
            NephosAssertionException.Assert(minValue != DateTime.MinValue, "The snapshot timestamp must be set!");
            context.ResultData = minValue;
        }
Beispiel #6
0
 public virtual void ValidateAndDeriveEffectiveAccessPolicy(SASIdentifier sasIdentifier)
 {
     NephosAssertionException.Assert(sasIdentifier.Id.Equals(this.SignedIdentifier));
     if (!this.SignedExpiry.HasValue && !sasIdentifier.AccessPolicy.SignedExpiry.HasValue)
     {
         throw new AuthenticationFailureException("Signed expiry must be specified in signature or SAS identifier");
     }
     if (!this.SignedPermission.HasValue && !sasIdentifier.AccessPolicy.SignedPermission.HasValue)
     {
         throw new AuthenticationFailureException("Signed permission must be specified in signature or SAS identifier");
     }
     if (this.SignedStart.HasValue && sasIdentifier.AccessPolicy.SignedStart.HasValue || this.SignedExpiry.HasValue && sasIdentifier.AccessPolicy.SignedExpiry.HasValue || this.SignedPermission.HasValue && sasIdentifier.AccessPolicy.SignedPermission.HasValue)
     {
         throw new AuthenticationFailureException("Access policy fields can be associated with signature or SAS identifier but not both");
     }
     if (sasIdentifier.AccessPolicy.SignedStart.HasValue)
     {
         this.SignedStart = new DateTime?(sasIdentifier.AccessPolicy.SignedStart.Value);
     }
     if (sasIdentifier.AccessPolicy.SignedExpiry.HasValue)
     {
         NephosAssertionException.Assert(!this.SignedExpiry.HasValue);
         this.SignedExpiry = new DateTime?(sasIdentifier.AccessPolicy.SignedExpiry.Value);
     }
     if (sasIdentifier.AccessPolicy.SignedPermission.HasValue)
     {
         NephosAssertionException.Assert(!this.SignedPermission.HasValue);
         this.SignedPermission = new SASPermission?(sasIdentifier.AccessPolicy.SignedPermission.Value);
     }
 }
Beispiel #7
0
        public bool ComputeSignatureAndCompare(byte[] stringToSign, SecretKeyListV3 keys)
        {
            bool flag;

            NephosAssertionException.Assert(stringToSign != null);
            NephosAssertionException.Assert(keys != null);
            if (keys.Count == 0)
            {
                throw new ArgumentException("Invalid number of keys");
            }
            bool flag1 = string.IsNullOrEmpty(this.KeyName);

            List <SecretKeyV3> .Enumerator enumerator = keys.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    SecretKeyV3 current = enumerator.Current;
                    if ((!flag1 || !current.IsDefault()) && !string.Equals(current.Name, this.KeyName) || !SASUtilities.ComputeSignatureAndCompare(stringToSign, current.Value, this.Signature))
                    {
                        continue;
                    }
                    this.KeyUsedForSigning = current;
                    flag = true;
                    return(flag);
                }
                return(false);
            }
            finally
            {
                ((IDisposable)enumerator).Dispose();
            }
            return(flag);
        }
Beispiel #8
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);
        }
Beispiel #9
0
        private IEnumerator <IAsyncResult> PutBlobImpl(string contentType, long contentLength, byte[] serviceMetadata, byte[] applicationMetadata, byte[][] blockIdList, BlockSource[] blockSourceList, byte[] contentMD5, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncIteratorContext <NoResults> context)
        {
            IAsyncResult asyncResult;
            bool         flag = contentLength == (long)-1;

            object[] objArray = new object[] { contentLength };
            NephosAssertionException.Assert(flag, "The contentLength we are going to pass into XStore for commiting blob is invalid: {0}", objArray);
            try
            {
                asyncResult = ((IListBlobObject)this.blob).BeginPutBlob(contentType, contentLength, serviceMetadata, applicationMetadata, blockIdList, blockSourceList, contentMD5, overwriteOption, Helpers.Convert(condition), context.GetResumeCallback(), context.GetResumeState("RealBlobObject.PutBlobImpl"));
            }
            catch (Exception exception)
            {
                StorageStamp.TranslateException(exception);
                throw;
            }
            yield return(asyncResult);

            try
            {
                this.blob.EndPutBlob(asyncResult);
            }
            catch (Exception exception1)
            {
                StorageStamp.TranslateException(exception1);
                throw;
            }
        }
Beispiel #10
0
 public MD5MismatchException(string message, byte[] specifiedMD5, byte[] calculatedMD5, Exception innerException) : base(message, innerException)
 {
     NephosAssertionException.Assert(specifiedMD5 != null);
     NephosAssertionException.Assert(calculatedMD5 != null);
     this.specifiedMD5  = specifiedMD5;
     this.calculatedMD5 = calculatedMD5;
 }
Beispiel #11
0
        public static TimeSpan GetSizeBasedTimeout(long dataSize, long dataRateForTimeout)
        {
            NephosAssertionException.Assert(dataRateForTimeout > (long)0);
            double num  = (double)dataRateForTimeout / 60000;
            int    num1 = (int)Math.Ceiling((double)dataSize / num);

            return(TimeSpan.FromMilliseconds((double)num1));
        }
Beispiel #12
0
 public VerbNotSupportedProtocolException(RestMethod calledMethod, ReadOnlyCollection <RestMethod> allowedMethods, Exception innerException) : base(string.Format(CultureInfo.InvariantCulture, "The method {0} is not supported for the specified resource. Refer to 'Allow' response header for the list of supported methods.", new object[] { calledMethod }), innerException)
 {
     NephosAssertionException.Assert(calledMethod != RestMethod.Unknown);
     NephosAssertionException.Assert(allowedMethods != null);
     NephosAssertionException.Assert(allowedMethods.Count > 0);
     this.calledMethod   = calledMethod;
     this.allowedMethods = allowedMethods;
 }
Beispiel #13
0
 protected void ValidateSignatureFormat(string signature)
 {
     NephosAssertionException.Assert(signature != null);
     if ((int)Convert.FromBase64String(signature).Length != SignedAccessHelper.Sha256HashSize / 8)
     {
         throw new AuthenticationFailureException("Signature size is invalid");
     }
 }
Beispiel #14
0
 public void Complete()
 {
     NephosAssertionException.Assert(this.outStreamAccumulator != null, "The underlying AccumulatorStream must not be null!");
     NephosAssertionException.Assert(this.xmlWriter != null, "The underlying XML Writer must not be null!");
     this.xmlWriter.Close();
     this.outStreamAccumulator.Dispose();
     this.xmlWriter            = null;
     this.outStreamAccumulator = null;
 }
Beispiel #15
0
 public static bool StringContains(string mainString, string stringToSearchFor)
 {
     NephosAssertionException.Assert(mainString != null);
     NephosAssertionException.Assert(stringToSearchFor != null);
     if (string.IsNullOrEmpty(mainString))
     {
         return(string.IsNullOrEmpty(stringToSearchFor));
     }
     return(mainString.IndexOf(stringToSearchFor, StringComparison.OrdinalIgnoreCase) != -1);
 }
Beispiel #16
0
        public IAsyncResult BeginPerformOperation(IAccountIdentifier accountId, string accountName, IDataServiceHost host, RequestStartedCallback requestStartedCallback, CheckPermissionDelegate checkPermissionCallback, QueryRowCommandPropertiesAvailableCallback queryRowCommandPropertiesAvailableCallback, Dictionary <string, string> continuationToken, ContinuationTokenAvailableCallback continuationTokenAvailableCallback, bool operationIsConditional, RequestContext requestContext, AsyncCallback callback, object state)
        {
            TableProtocolHead tableProtocolHead = host as TableProtocolHead;

            NephosAssertionException.Assert(tableProtocolHead != null, "Expecting host to be instance of TableProtocolHead.");
            AsyncIteratorContext <NoResults> asyncIteratorContext = new AsyncIteratorContext <NoResults>("TableManager.PerformOperation", callback, state);

            asyncIteratorContext.Begin(this.PerformOperationImpl(accountId, accountName, tableProtocolHead, requestStartedCallback, checkPermissionCallback, queryRowCommandPropertiesAvailableCallback, continuationToken, continuationTokenAvailableCallback, operationIsConditional, requestContext, asyncIteratorContext));
            return(asyncIteratorContext);
        }
Beispiel #17
0
 public SignedAccessHelper(Microsoft.Cis.Services.Nephos.Common.RequestContext requestContext, NephosUriComponents uriComponents)
 {
     NephosAssertionException.Assert(requestContext != null);
     NephosAssertionException.Assert(uriComponents != null);
     NephosAssertionException.Assert(requestContext.QueryParameters != null);
     this.QueryParams    = requestContext.QueryParameters;
     this.RequestContext = requestContext;
     this.UriComponents  = uriComponents;
     this.SignedProtocol = SasProtocol.All;
 }
Beispiel #18
0
 public AccountIdentifier(IStorageAccount account, SecretKeyPermissions keyUsedPermissions)
 {
     if (account == null)
     {
         throw new ArgumentNullException("account", "account cannot be null");
     }
     NephosAssertionException.Assert(account.Permissions.HasValue, "account.Permissions cannot be null");
     this.AccountName        = account.Name;
     this.IsSecondaryAccess  = account.IsSecondaryAccess;
     this.Permissions        = account.Permissions.Value;
     this.KeyUsedPermissions = keyUsedPermissions;
 }
Beispiel #19
0
        public static bool ComputeSignatureAndCompare(byte[] stringToSign, byte[] key, string expectedSignature)
        {
            bool flag;

            NephosAssertionException.Assert(key != null);
            using (HMAC hMAC = HMACCryptoCache.Instance.Acquire(key))
            {
                byte[] numArray = hMAC.ComputeHash(stringToSign);
                NephosAssertionException.Assert((int)numArray.Length == hMAC.HashSize / 8);
                flag = AuthenticationManager.AreSignaturesEqual(Convert.ToBase64String(numArray), expectedSignature);
            }
            return(flag);
        }
Beispiel #20
0
 public object GetService(Type serviceType)
 {
     if (serviceType == null)
     {
         throw new ArgumentNullException("serviceType");
     }
     NephosAssertionException.Assert(this.dataSource != null, "DataSource has not been created yet, but IServiceProvider.GetService was called");
     if (!(serviceType == typeof(IDataServiceUpdateProvider)) && !(serviceType == typeof(IDataServiceQueryProvider)) && !(serviceType == typeof(IDataServiceMetadataProvider)) && !(serviceType == typeof(IUpdatable)))
     {
         return(null);
     }
     return(this.dataSource);
 }
Beispiel #21
0
 public static void SignedKeyParamsParser(SupportedAuthScheme scheme, string parameter, NephosUriComponents uriComponents, out string accountName, out string signature)
 {
     NephosAssertionException.Assert(scheme.Equals(SupportedAuthScheme.SignedKey));
     NephosAssertionException.Assert((uriComponents == null ? false : !string.IsNullOrEmpty(uriComponents.AccountName)));
     if (string.IsNullOrEmpty(parameter))
     {
         CultureInfo invariantCulture = CultureInfo.InvariantCulture;
         object[]    objArray         = new object[] { "Authorization", string.Format("{0} {1}", scheme, parameter) };
         throw new InvalidAuthenticationInfoException(string.Format(invariantCulture, "{0} value '{1}' is invalid.", objArray));
     }
     accountName = uriComponents.AccountName;
     signature   = parameter;
 }
Beispiel #22
0
 public static byte[] ComputeSignedKey(byte[] stringToSign, byte[] key)
 {
     byte[] numArray;
     NephosAssertionException.Assert((stringToSign == null ? false : (int)stringToSign.Length > 0));
     NephosAssertionException.Assert(key != null);
     using (HMACSHA512 hMACSHA512 = new HMACSHA512(key))
     {
         byte[] numArray1 = hMACSHA512.ComputeHash(stringToSign);
         NephosAssertionException.Assert((int)numArray1.Length == hMACSHA512.HashSize / 8);
         numArray = numArray1;
     }
     return(numArray);
 }
Beispiel #23
0
 public static void SharedKeyParamsParser(SupportedAuthScheme scheme, string parameter, NephosUriComponents uriComponents, out string accountName, out string signature)
 {
     NephosAssertionException.Assert((scheme.Equals(SupportedAuthScheme.SharedKey) ? true : scheme.Equals(SupportedAuthScheme.SharedKeyLite)));
     NephosAssertionException.Assert(!string.IsNullOrEmpty(parameter));
     string[] strArrays = parameter.Split(HttpRequestAccessorCommon.colonDelimiter, StringSplitOptions.RemoveEmptyEntries);
     if ((int)strArrays.Length != 2)
     {
         CultureInfo invariantCulture = CultureInfo.InvariantCulture;
         object[]    objArray         = new object[] { "Authorization", string.Format("{0} {1}", scheme, parameter) };
         throw new InvalidAuthenticationInfoException(string.Format(invariantCulture, "{0} value '{1}' is invalid.", objArray));
     }
     accountName = strArrays[0];
     signature   = strArrays[1];
 }
Beispiel #24
0
        private IEnumerator <IAsyncResult> AuthorizeRequestImpl(IAccountIdentifier requestor, string resourceAccount, string resourceContainer, string resourceIdentifier, PermissionLevel requestedPermission, SASAuthorizationParameters requestedSasParameters, AuthorizationInformation authorizationInfo, TimeSpan timeout, AsyncIteratorContext <AuthorizationResult> context)
        {
            Duration     startingNow = Duration.StartingNow;
            IAsyncResult asyncResult = this.BeginSharedKeyAuthorization(requestor, resourceAccount, resourceContainer, resourceIdentifier, requestedPermission, authorizationInfo, startingNow.Remaining(timeout), context.GetResumeCallback(), context.GetResumeState("NephosAuthorizationManager.AuthorizeRequestImpl"));

            yield return(asyncResult);

            AuthorizationResult authorizationResult = this.EndAuthorizeRequest(asyncResult);
            bool authorized = authorizationResult.Authorized;

            if (!authorized || !(requestor is SignedAccessAccountIdentifier) && !(requestor is AccountSasAccessIdentifier))
            {
                context.ResultData = authorizationResult;
            }
            else
            {
                NephosAssertionException.Assert((requestor is SignedAccessAccountIdentifier ? true : requestor is AccountSasAccessIdentifier));
                if (!(requestor is SignedAccessAccountIdentifier))
                {
                    if (!(requestor is AccountSasAccessIdentifier))
                    {
                        throw new NephosUnauthorizedAccessException("Signed access not supported for this request", resourceAccount, resourceContainer, resourceIdentifier, requestor, requestedPermission, AuthorizationFailureReason.InvalidOperationSAS);
                    }
                    if ((requestedSasParameters.SupportedSasTypes & SasType.AccountSas) != SasType.AccountSas)
                    {
                        throw new NephosUnauthorizedAccessException("Account signed access not supported for this request", resourceAccount, resourceContainer, resourceIdentifier, requestor, requestedPermission, AuthorizationFailureReason.InvalidOperationSAS);
                    }
                    if (requestedSasParameters.SignedPermission == SASPermission.None)
                    {
                        throw new ArgumentException("signedPerrmission");
                    }
                    authorizationResult = this.AuthorizeAccountSignedAccessRequest(requestor as AccountSasAccessIdentifier, resourceAccount, resourceContainer, resourceIdentifier, requestedPermission, requestedSasParameters);
                    context.ResultData  = authorizationResult;
                }
                else
                {
                    if ((requestedSasParameters.SupportedSasTypes & SasType.ResourceSas) != SasType.ResourceSas)
                    {
                        throw new NephosUnauthorizedAccessException("Signed access not supported for this request", resourceAccount, resourceContainer, resourceIdentifier, requestor, requestedPermission, AuthorizationFailureReason.InvalidOperationSAS);
                    }
                    if (requestedSasParameters.SignedPermission == SASPermission.None)
                    {
                        throw new ArgumentException("signedPerrmission");
                    }
                    authorizationResult = this.AuthorizeResourceSignedAccessRequest(requestor as SignedAccessAccountIdentifier, resourceAccount, resourceContainer, resourceIdentifier, requestedPermission, requestedSasParameters.SignedPermission);
                    context.ResultData  = authorizationResult;
                }
            }
        }
Beispiel #25
0
        private static string GetCanonicalizedResource(NephosUriComponents uriComponents, string tableName, string signedVersion)
        {
            NephosAssertionException.Assert(!string.IsNullOrEmpty(uriComponents.AccountName));
            NephosAssertionException.Assert(!string.IsNullOrEmpty(tableName));
            StringBuilder stringBuilder = new StringBuilder();

            if (signedVersion != null && VersioningHelper.CompareVersions(signedVersion, "2015-02-21") >= 0)
            {
                stringBuilder.Append("/table");
            }
            stringBuilder.Append("/");
            stringBuilder.Append(uriComponents.AccountName);
            stringBuilder.Append("/");
            stringBuilder.Append(tableName.ToLower());
            return(stringBuilder.ToString());
        }
Beispiel #26
0
        protected override IEnumerator <IAsyncResult> DeleteMessageImpl(IAccountIdentifier identity, string account, string queue, string messageId, byte[] popReceipt, TimeSpan?timeout, RequestContext requestContext, AsyncIteratorContext <NoResults> context)
        {
            RemainingTime remainingTime = new RemainingTime(timeout);
            SASAuthorizationParameters sASAuthorizationParameter = new SASAuthorizationParameters()
            {
                SupportedSasTypes  = SasType.ResourceSas | SasType.AccountSas,
                SignedResourceType = SasResourceType.Object,
                SignedPermission   = SASPermission.Process
            };
            SASAuthorizationParameters sASAuthorizationParameter1 = sASAuthorizationParameter;

            NephosAssertionException.Assert(popReceipt != null);
            IAsyncResult asyncResult = this.BeginGetQueue(identity, account, queue, PermissionLevel.Delete, sASAuthorizationParameter1, remainingTime, requestContext, context.GetResumeCallback(), context.GetResumeState("QueueManager.DeleteMessageImpl"));

            yield return(asyncResult);

            IQueueContainer operationStatus = this.EndGetQueue(asyncResult);

            if (requestContext != null)
            {
                operationStatus.OperationStatus = requestContext.OperationStatus;
            }
            try
            {
                Guid guid = new Guid(messageId);
            }
            catch (Exception exception)
            {
                throw new MessageNotFoundException("Invalid message name", exception);
            }
            IQueueMessageReceipt queueMessageReceipt = this.DecodeReceipt(popReceipt, new Guid(messageId));

            operationStatus.Timeout = remainingTime;
            asyncResult             = operationStatus.BeginDeleteMessage(queueMessageReceipt, context.GetResumeCallback(), context.GetResumeState("QueueManager.DeleteMessageImpl"));
            yield return(asyncResult);

            bool flag = operationStatus.EndDeleteMessage(asyncResult);
            IStringDataEventStream verboseDebug = Logger <IRestProtocolHeadLogger> .Instance.VerboseDebug;

            object[] str = new object[] { flag, queueMessageReceipt.ToString() };
            verboseDebug.Log("DeleteMessage response: status={0} message={1}", str);
            if (!flag)
            {
                throw new MessageNotFoundException("The message could not be deleted or pop receipt invalid.");
            }
        }
Beispiel #27
0
        public void ValidateNonRevocableAccessWindow()
        {
            DateTime dateTime = (base.SignedStart.HasValue ? base.SignedStart.Value : DateTime.UtcNow);

            NephosAssertionException.Assert(true);
            DateTime value = base.SignedExpiry.Value;

            NephosAssertionException.Assert(true);
            if (dateTime >= base.SignedExpiry.Value)
            {
                DateTime value1 = base.SignedExpiry.Value;
                throw new AuthenticationFailureException(string.Format("Signed expiry time [{0}] must be after signed start time [{1}]", value1.ToString("R"), dateTime.ToString("R")));
            }
            if (!this.IsAtLeastFeb2012SasVersion && !((base.SignedExpiry.Value - dateTime) <= BlobSignedAccessHelper.MaxAllowedNonRevocableAccessTimeWindowForPreFeb2012Version))
            {
                string   str       = dateTime.ToString("R");
                DateTime dateTime1 = base.SignedExpiry.Value;
                throw new AuthenticationFailureException(string.Format("Access without signed identifier cannot have time window more than 1 hour: Start [{0}] - Expiry [{1}]", str, dateTime1.ToString("R")));
            }
        }
Beispiel #28
0
        private static string GetCanonicalizedResource(NephosUriComponents uriComponents, SASAccessLevel signedResource, string signedVersion)
        {
            NephosAssertionException.Assert(!string.IsNullOrEmpty(uriComponents.AccountName));
            NephosAssertionException.Assert(!string.IsNullOrEmpty(uriComponents.ContainerName));
            StringBuilder stringBuilder = new StringBuilder();

            if (signedVersion != null && VersioningHelper.CompareVersions(signedVersion, "2015-02-21") >= 0)
            {
                stringBuilder.Append("/blob");
            }
            stringBuilder.Append("/");
            stringBuilder.Append(uriComponents.AccountName);
            stringBuilder.Append("/");
            stringBuilder.Append(uriComponents.ContainerName);
            if (signedResource == SASAccessLevel.Blob)
            {
                NephosAssertionException.Assert(!string.IsNullOrEmpty(uriComponents.RemainingPart));
                stringBuilder.Append("/");
                stringBuilder.Append(uriComponents.RemainingPart);
            }
            return(stringBuilder.ToString());
        }
Beispiel #29
0
        public static TimeSpan GetSizeBasedTimeout(long contentLength, TimeSpan userTimeout, TimeSpan minimumTimeout, long dataRateForTimeout)
        {
            NephosAssertionException.Assert(dataRateForTimeout > (long)0);
            int      num      = (int)Math.Ceiling((double)contentLength / (double)dataRateForTimeout);
            TimeSpan timeSpan = TimeSpan.FromMinutes((double)Math.Max((int)minimumTimeout.TotalMinutes, num));

            if (userTimeout > timeSpan)
            {
                IStringDataEventStream verbose = Logger <IRestProtocolHeadLogger> .Instance.Verbose;
                object[] totalSeconds          = new object[] { (long)userTimeout.TotalSeconds, (long)timeSpan.TotalSeconds, contentLength, dataRateForTimeout };
                verbose.Log("SecurityWarning: Reducing user timeout from {0} seconds to {1} seconds based on size {2} bytes and a rate of {3} bytes per minute.", totalSeconds);
            }
            else
            {
                timeSpan = userTimeout;
            }
            IStringDataEventStream stringDataEventStream = Logger <IRestProtocolHeadLogger> .Instance.Verbose;

            object[] objArray = new object[] { timeSpan.TotalSeconds, contentLength, minimumTimeout.TotalSeconds, userTimeout.TotalSeconds, dataRateForTimeout };
            stringDataEventStream.Log("GetSizeBasedTimeout (seconds) >> Returning timeout '{0}' based on contentLength {1},  minimumTimeout '{2}', user timeout '{3}' and a rate of {4} bytes per minute.", objArray);
            return(timeSpan);
        }
Beispiel #30
0
        public virtual void PerformSignedAccessAuthenticationSecondPhaseValidations()
        {
            bool flag;

            if (!this.SignedPermission.HasValue)
            {
                flag = false;
            }
            else
            {
                SASPermission?signedPermission = this.SignedPermission;
                flag = (signedPermission.GetValueOrDefault() != SASPermission.None ? true : !signedPermission.HasValue);
            }
            NephosAssertionException.Assert(flag);
            try
            {
                NephosAssertionException.Assert(this.SignedExpiry.HasValue);
                this.ValidateAccessTimeframe((this.SignedStart.HasValue ? this.SignedStart.Value : DateTime.UtcNow), this.SignedExpiry.Value);
            }
            catch (FormatException formatException)
            {
                throw new AuthenticationFailureException("Signature fields not well formed.", formatException);
            }
        }