Example #1
0
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param>
        /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.InvariantCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string            resourceName = this.GetCanonicalName(true /* ignoreSnapshotTime */);
            StorageAccountKey accountKey   = this.ServiceClient.Credentials.Key;

#if ALL_SERVICES
            string signature = SharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, OperationContext.StorageVersion ?? Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, accountKey.KeyValue);
#else
            string signature = BlobSharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, accountKey.KeyValue);
#endif

            // Future resource type changes from "c" => "container"
#if ALL_SERVICES
            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, "b", signature, accountKey.KeyName, OperationContext.StorageVersion ?? Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange);
#else
            UriQueryBuilder builder = BlobSharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, "b", signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange);
#endif

            return(builder.ToString());
        }
        /// <summary>
        /// Get blob shared access signature
        /// </summary>
        /// <param name="blob">CloudBlob object</param>
        /// <param name="accessPolicy">SharedAccessBlobPolicy object</param>
        /// <param name="policyIdentifier">The existing policy identifier.</param>
        /// <returns></returns>
        private string GetBlobSharedAccessSignature(CloudBlob blob, SharedAccessBlobPolicy accessPolicy, string policyIdentifier, SharedAccessProtocol?protocol, IPAddressOrRange iPAddressOrRange)
        {
            CloudBlobContainer container = blob.Container;

            return(blob.GetSharedAccessSignature(accessPolicy, null, policyIdentifier, protocol, iPAddressOrRange));
        }
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="startPartitionKey">The start partition key, or <c>null</c>.</param>
        /// <param name="startRowKey">The start row key, or <c>null</c>.</param>
        /// <param name="endPartitionKey">The end partition key, or <c>null</c>.</param>
        /// <param name="endRowKey">The end row key, or <c>null</c>.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string resourceName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string         permissions = null;
            DateTimeOffset?startTime   = null;
            DateTimeOffset?expiryTime  = null;

            if (policy != null)
            {
                permissions = SharedAccessTablePolicy.PermissionsToString(policy.Permissions);
                startTime   = policy.SharedAccessStartTime;
                expiryTime  = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedIP + "\n" +
            ////                     signedProtocol + "\n" +
            ////                     signedversion + "\n" +
            ////                     startpk + "\n" +
            ////                     startrk + "\n" +
            ////                     endpk + "\n" +
            ////                     endrk
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}",
                permissions,
                GetDateTimeOrEmpty(startTime),
                GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                GetProtocolString(protocols),
                sasVersion,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
 public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// Returns a shared access signature for the share.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessFilePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="groupPolicyIdentifier">A share-level access policy.</param>
        /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param>
        /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
        public string GetSharedAccessSignature(SharedAccessFilePolicy policy, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string            resourceName   = this.GetSharedAccessCanonicalName();
            StorageAccountKey accountKey     = this.ServiceClient.Credentials.Key;
            string            signature      = SharedAccessSignatureHelper.GetHash(policy, null /* headers */, groupPolicyIdentifier, resourceName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, accountKey.KeyValue);
            string            accountKeyName = accountKey.KeyName;

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, null /* headers */, groupPolicyIdentifier, "s", signature, accountKeyName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange);

            return(builder.ToString());
        }
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param>
        /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.InvariantCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = this.GetCanonicalName(true /* ignoreSnapshotTime */);
            StorageAccountKey accountKey = this.ServiceClient.Credentials.Key;
            string signature = SharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, accountKey.KeyValue);

            // Future resource type changes from "c" => "container"
            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, "b", signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange);

            return builder.ToString();
        }
 internal static string GetHash(SharedAccessFilePolicy policy, SharedAccessFileHeaders headers, string accessPolicyIdentifier, string resourceName, string sasVersion, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange, byte[] keyValue)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param>
        /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.InvariantCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string            resourceType = this.IsSnapshot ? Constants.QueryConstants.BlobSnapshotResourceType : Constants.QueryConstants.BlobResourceType;
            string            resourceName = this.GetCanonicalName(true /* ignoreSnapshotTime */);
            StorageAccountKey accountKey   = this.ServiceClient.Credentials.Key;

            string          signature = BlobSharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, accountKey.KeyValue, resourceType, this.SnapshotTime);
            UriQueryBuilder builder   = BlobSharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, resourceType, signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange);

            return(builder.ToString());
        }
 internal static UriQueryBuilder GetSignature(SharedAccessTablePolicy policy, string tableName, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey, string signature, string accountKeyName, string sasVersion, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
 internal static string GetHash(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey, string resourceName, string sasVersion, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange, byte[] keyValue)
 {
     throw new System.NotImplementedException();
 }
 internal static UriQueryBuilder GetSignature(SharedAccessFilePolicy policy, SharedAccessFileHeaders headers, string accessPolicyIdentifier, string resourceType, string signature, string accountKeyName, string sasVersion, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
Example #13
0
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a blob returned with this SAS.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <param name="resource">Resource type identifier (e.g. "b", "c", "bs").</param>
        /// <param name="snapshotTimestamp">Timestamp of the snapshot for a snapshot-only SAS, null otherwise.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            byte[] keyValue,
            string resource,
            DateTimeOffset?snapshotTimestamp = null)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);
            CommonUtility.AssertNotNullOrEmpty("resource", resource);

            string         permissions = null;
            DateTimeOffset?startTime   = null;
            DateTimeOffset?expiryTime  = null;

            if (policy != null)
            {
                permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                startTime   = policy.SharedAccessStartTime;
                expiryTime  = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedIP + "\n" +
            ////                     signedProtocol + "\n" +
            ////                     signedversion + "\n" +
            ////                     signedresource + "\n" +
            ////                     signedTimeStamp + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////

            string cacheControl       = null;
            string contentDisposition = null;
            string contentEncoding    = null;
            string contentLanguage    = null;
            string contentType        = null;

            if (headers != null)
            {
                cacheControl       = headers.CacheControl;
                contentDisposition = headers.ContentDisposition;
                contentEncoding    = headers.ContentEncoding;
                contentLanguage    = headers.ContentLanguage;
                contentType        = headers.ContentType;
            }

            string snapTime = null;

            if (snapshotTimestamp.HasValue)
            {
                snapTime = Request.ConvertDateTimeToSnapshotString(snapshotTimestamp.Value);
            }

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}\n{13}\n{14}",
                permissions,
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(startTime),
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                SharedAccessSignatureHelper.GetProtocolString(protocols),
                sasVersion,
                resource,
                snapTime,
                cacheControl,
                contentDisposition,
                contentEncoding,
                contentLanguage,
                contentType);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
Example #14
0
        /// <summary>
        /// Get the signature hash embedded inside the User Delegation Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a blob returned with this SAS.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="resourceIdentifier">Resource type id string.</param>
        /// <param name="snapTime">Time of snapshot if applicable.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="delegationKey">The user delegaion key used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string resourceName,
            string sasVersion,
            string resourceIdentifier,
            DateTimeOffset?snapTime,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            UserDelegationKey delegationKey)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            CommonUtility.AssertNotNull("delegationKey", delegationKey);
            CommonUtility.AssertNotNull("delegationKey.SignedOid", delegationKey.SignedOid);
            CommonUtility.AssertNotNull("delegationKey.SignedTid", delegationKey.SignedTid);
            CommonUtility.AssertNotNull("delegationKey.SignedStart", delegationKey.SignedStart);
            CommonUtility.AssertNotNull("delegationKey.SignedExpiry", delegationKey.SignedExpiry);
            CommonUtility.AssertNotNullOrEmpty("delegationKey.SignedService", delegationKey.SignedService);
            CommonUtility.AssertNotNullOrEmpty("delegationKey.SignedVersion", delegationKey.SignedVersion);
            CommonUtility.AssertNotNullOrEmpty("delegationKey.Value", delegationKey.Value);

            CommonUtility.AssertNotNull("policy", policy);
            CommonUtility.AssertNotNull("policy.SharedAccessExpiryTime", policy.SharedAccessExpiryTime);
            CommonUtility.AssertNotNullOrEmpty("policy.Permissions", SharedAccessBlobPolicy.PermissionsToString(policy.Permissions));

            string         permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
            DateTimeOffset?startTime   = policy.SharedAccessStartTime;
            DateTimeOffset?expiryTime  = policy.SharedAccessExpiryTime;

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedoid + "\n" +
            ////                     signedtid + "\n" +
            ////                     signedkeystart + "\n" +
            ////                     signedkeyexpiry + "\n" +
            ////                     signedkeyservice + "\n" +
            ////                     signedkeyverion + "\n" +
            ////                     signedIP + "\n" +
            ////                     signedProtocol + "\n" +
            ////                     signedversion + "\n" +
            ////                     signedResourceIdentifier + "\n" +
            ////                     signedTimeStamp + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))

            string cacheControl       = null;
            string contentDisposition = null;
            string contentEncoding    = null;
            string contentLanguage    = null;
            string contentType        = null;

            if (headers != null)
            {
                cacheControl       = headers.CacheControl;
                contentDisposition = headers.ContentDisposition;
                contentEncoding    = headers.ContentEncoding;
                contentLanguage    = headers.ContentLanguage;
                contentType        = headers.ContentType;
            }

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}\n{13}\n{14}\n{15}\n{16}\n{17}\n{18}\n{19}",
                permissions,
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(startTime),
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(expiryTime),
                resourceName,
                delegationKey.SignedOid,
                delegationKey.SignedTid,
                delegationKey.SignedStart.Value.UtcDateTime.ToString(Constants.DateTimeFormatter),
                delegationKey.SignedExpiry.Value.UtcDateTime.ToString(Constants.DateTimeFormatter),
                delegationKey.SignedService,
                delegationKey.SignedVersion,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                SharedAccessSignatureHelper.GetProtocolString(protocols),
                sasVersion,
                resourceIdentifier,
                snapTime.ToString(),
                cacheControl,
                contentDisposition,
                contentEncoding,
                contentLanguage,
                contentType);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(Convert.FromBase64String(delegationKey.Value), stringToSign));
        }
Example #15
0
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for blobs
        /// </summary>
        /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
        /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
        /// that should be accepted by the service</param>
        public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                CloudBlob blob;
                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                byte[]         data      = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                blockBlob.UploadFromByteArray(data, 0, 4);

                // The plan then is to use an incorrect IP address to make a call to the service
                // ensure that we get an error message
                // parse the error message to get my actual IP (as far as the service sees)
                // then finally test the success case to ensure we can actually make requests

                IPAddressOrRange   ipAddressOrRange = generateInitialIPAddressOrRange();
                string             blockBlobToken   = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                StorageCredentials blockBlobSAS     = new StorageCredentials(blockBlobToken);
                Uri        blockBlobSASUri          = blockBlobSAS.TransformUri(blockBlob.Uri);
                StorageUri blockBlobSASStorageUri   = blockBlobSAS.TransformUri(blockBlob.StorageUri);

                blob = new CloudBlob(blockBlobSASUri);
                byte[]           target    = new byte[4];
                OperationContext opContext = new OperationContext();
                IPAddress        actualIP  = null;

                bool exceptionThrown = false;
                try
                {
                    blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    //The IP should not be included in the error details for security reasons
                    Assert.IsNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange       = null;
                blockBlobToken         = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                blockBlobSAS           = new StorageCredentials(blockBlobToken);
                blockBlobSASUri        = blockBlobSAS.TransformUri(blockBlob.Uri);
                blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);


                blob = new CloudBlob(blockBlobSASUri);
                blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = new CloudBlob(blockBlobSASStorageUri, null, null);
                blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
Example #16
0
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for blobs
        /// </summary>
        /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
        /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
        /// that should be accepted by the service</param>
        public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                CloudBlob blob;
                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                byte[]         data      = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                blockBlob.UploadFromByteArray(data, 0, 4);

                // The plan then is to use an incorrect IP address to make a call to the service
                // ensure that we get an error message
                // parse the error message to get my actual IP (as far as the service sees)
                // then finally test the success case to ensure we can actually make requests

                IPAddressOrRange   ipAddressOrRange = generateInitialIPAddressOrRange();
                string             blockBlobToken   = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                StorageCredentials blockBlobSAS     = new StorageCredentials(blockBlobToken);
                Uri        blockBlobSASUri          = blockBlobSAS.TransformUri(blockBlob.Uri);
                StorageUri blockBlobSASStorageUri   = blockBlobSAS.TransformUri(blockBlob.StorageUri);

                blob = new CloudBlob(blockBlobSASUri);
                byte[]           target    = new byte[4];
                OperationContext opContext = new OperationContext();
                IPAddress        actualIP  = null;
                opContext.ResponseReceived += (sender, e) =>
                {
                    Stream stream = e.Response.GetResponseStream();
                    stream.Seek(0, SeekOrigin.Begin);
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string    text      = reader.ReadToEnd();
                        XDocument xdocument = XDocument.Parse(text);
                        actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
                    }
                };

                bool exceptionThrown = false;
                try
                {
                    blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange       = generateFinalIPAddressOrRange(actualIP);
                blockBlobToken         = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                blockBlobSAS           = new StorageCredentials(blockBlobToken);
                blockBlobSASUri        = blockBlobSAS.TransformUri(blockBlob.Uri);
                blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);


                blob = new CloudBlob(blockBlobSASUri);
                blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = new CloudBlob(blockBlobSASStorageUri, null, null);
                blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
Example #17
0
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
Example #18
0
        public void CloudFileSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();
                CloudFile file;
                SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
                {
                    Permissions            = SharedAccessFilePermissions.Read,
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudFile fileWithKey = share.GetRootDirectoryReference().GetFileReference("filefile");
                byte[]    data        = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                fileWithKey.UploadFromByteArray(data, 0, 4);

                // We need an IP address that will never be a valid source
                IPAddressOrRange   ipAddressOrRange = generateInitialIPAddressOrRange();
                string             fileToken        = fileWithKey.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                StorageCredentials fileSAS          = new StorageCredentials(fileToken);
                Uri        fileSASUri        = fileSAS.TransformUri(fileWithKey.Uri);
                StorageUri fileSASStorageUri = fileSAS.TransformUri(fileWithKey.StorageUri);

                file = new CloudFile(fileSASUri);
                byte[]           target    = new byte[4];
                OperationContext opContext = new OperationContext();
                IPAddress        actualIP  = null;
                opContext.ResponseReceived += (sender, e) =>
                {
                    Stream stream = HttpResponseParsers.GetResponseStream(e.Response);
                    stream.Seek(0, SeekOrigin.Begin);
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string    text      = reader.ReadToEnd();
                        XDocument xdocument = XDocument.Parse(text);
                        actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
                    }
                };

                bool exceptionThrown = false;
                try
                {
                    file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    //The IP should not be included in the error details for security reasons
                    Assert.IsNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange  = null;
                fileToken         = fileWithKey.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                fileSAS           = new StorageCredentials(fileToken);
                fileSASUri        = fileSAS.TransformUri(fileWithKey.Uri);
                fileSASStorageUri = fileSAS.TransformUri(fileWithKey.StorageUri);

                file = new CloudFile(fileSASUri);
                file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }

                Assert.IsTrue(file.StorageUri.PrimaryUri.Equals(fileWithKey.Uri));
                Assert.IsNull(file.StorageUri.SecondaryUri);

                file = new CloudFile(fileSASStorageUri, null);
                file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }

                Assert.IsTrue(file.StorageUri.Equals(fileWithKey.StorageUri));
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     return(this.failoverExecutor.Execute(x => x.GetSharedAccessSignature(policy, headers, groupPolicyIdentifier, protocols, ipAddressOrRange)));
 }
        /// <summary>
        /// Get blob shared access signature
        /// </summary>
        /// <param name="blob">CloudBlob object</param>
        /// <param name="accessPolicy">SharedAccessBlobPolicy object</param>
        /// <param name="policyIdentifier">The existing policy identifier.</param>
        /// <returns></returns>
        private string GetBlobSharedAccessSignature(CloudBlob blob, SharedAccessBlobPolicy accessPolicy, string policyIdentifier, SharedAccessProtocol?protocol, IPAddressOrRange iPAddressOrRange, bool generateUserDelegationSas)
        {
            CloudBlobContainer container = blob.Container;

            if (generateUserDelegationSas)
            {
                Azure.Storage.UserDelegationKey userDelegationKey = Channel.GetUserDelegationKey(accessPolicy.SharedAccessStartTime, accessPolicy.SharedAccessExpiryTime, null, null, OperationContext);
                return(blob.GetUserDelegationSharedAccessSignature(userDelegationKey, accessPolicy, null, protocol, iPAddressOrRange));
            }
            else
            {
                return(blob.GetSharedAccessSignature(accessPolicy, null, policyIdentifier, protocol, iPAddressOrRange));
            }
        }
        /// <summary>
        /// Returns a shared access signature for the queue.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param>
        /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
        public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = this.GetCanonicalName();
            StorageAccountKey accountKey = this.ServiceClient.Credentials.Key;

            string signature = SharedAccessSignatureHelper.GetHash(
                policy,
                accessPolicyIdentifier,
                resourceName,
                Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange,
                accountKey.KeyValue);

            string accountKeyName = accountKey.KeyName;

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(
                policy,
                accessPolicyIdentifier,
                signature,
                accountKeyName,
                Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange);

            return builder.ToString();
        }
Example #22
0
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, SharedAccessProtocol?protocols = null, IPAddressOrRange ipAddressOrRange = null)
 {
     return(_queue.GetSharedAccessSignature(policy, accessPolicyIdentifier, protocols, ipAddressOrRange));
 }