예제 #1
0
        /// <summary>
        /// Create a blob SAS build from Blob Object
        /// </summary>
        public static BlobSasBuilder SetBlobSasBuilder_FromBlob(BlobBaseClient blobClient,
                                                                BlobSignedIdentifier signedIdentifier = null,
                                                                string Permission             = null,
                                                                DateTime?StartTime            = null,
                                                                DateTime?ExpiryTime           = null,
                                                                string iPAddressOrRange       = null,
                                                                SharedAccessProtocol?Protocol = null,
                                                                string EncryptionScope        = null)
        {
            BlobSasBuilder sasBuilder = SetBlobSasBuilder(blobClient.BlobContainerName,
                                                          blobClient.Name,
                                                          signedIdentifier,
                                                          Permission,
                                                          StartTime,
                                                          ExpiryTime,
                                                          iPAddressOrRange,
                                                          Protocol,
                                                          EncryptionScope);

            if (Util.GetVersionIdFromBlobUri(blobClient.Uri) != null)
            {
                sasBuilder.BlobVersionId = Util.GetVersionIdFromBlobUri(blobClient.Uri);
            }
            if (Util.GetSnapshotTimeFromBlobUri(blobClient.Uri) != null)
            {
                sasBuilder.Snapshot = Util.GetSnapshotTimeFromBlobUri(blobClient.Uri).Value.UtcDateTime.ToString("o");
            }
            return(sasBuilder);
        }
예제 #2
0
        public static string GetSharedAccessSignature(
            CloudBlob blob,
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string groupPolicyIdentifier,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            string targetStorageVersion)
        {
            if (!blob.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, "CannotCreateSASWithoutAccountKey");
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = GetCanonicalName(blob, targetStorageVersion);

            string signature = GetHash(policy,
                                       headers,
                                       groupPolicyIdentifier,
                                       resourceName,
                                       targetStorageVersion,
                                       protocols,
                                       ipAddressOrRange,
                                       blob.ServiceClient.Credentials.ExportKey());

            // Future resource type changes from "c" => "container"
            UriQueryBuilder builder = GetSignature(policy, headers, groupPolicyIdentifier, "b", signature, null, targetStorageVersion, protocols, ipAddressOrRange);

            return(builder.ToString());
        }
예제 #3
0
        private string GenerateAndValidateAccountSAS(
            SharedAccessAccountServices service,
            SharedAccessAccountResourceTypes resourceType,
            string permission,
            SharedAccessProtocol?protocol = null,
            string iPAddressOrRange       = null,
            DateTime?startTime            = null, DateTime?expiryTime = null)
        {
            Test.Assert(CommandAgent.NewAzureStorageAccountSAS(
                            service, resourceType, permission, protocol, iPAddressOrRange, startTime, expiryTime), "Should succeeded in generating an account sas with full permissions, services and resource types");

            string sasToken;

            if (lang == Language.PowerShell)
            {
                sasToken = CommandAgent.Output[0][Constants.SASTokenKey].ToString();
            }
            else
            {
                sasToken = "?" + CommandAgent.Output[0][Constants.SASTokenKeyNode];
            }
            AccountSASUtils.ValidateAccountSAS(
                service, resourceType, permission, protocol, iPAddressOrRange, startTime, expiryTime, sasToken);

            return(sasToken);
        }
예제 #4
0
        /// <summary>
        /// Get the complete query builder for creating the Shared Access Signature query.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="signature">The signature to use.</param>
        /// <param name="accountKeyName">The name of the key used to create the signature, or <c>null</c> if the key is implicit.</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>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetSignature(
            SharedAccessQueuePolicy policy,
            string accessPolicyIdentifier,
            string signature,
            string accountKeyName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange)
        {
            CommonUtility.AssertNotNull("signature", signature);

            UriQueryBuilder builder = new UriQueryBuilder();

            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, sasVersion);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, accessPolicyIdentifier);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKey, accountKeyName);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedProtocols, GetProtocolString(protocols));
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIP, ipAddressOrRange == null ? null : ipAddressOrRange.ToString());

            if (policy != null)
            {
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime));
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime));

                string permissions = SharedAccessQueuePolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
                }
            }

            return(builder);
        }
예제 #5
0
        /// <summary>
        /// Get the complete query builder for creating the Shared Access Signature query.
        /// </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="resourceType">"b" for blobs, "bs" for blob snapshots, or "c" for containers.</param>
        /// <param name="signature">The signature to use.</param>
        /// <param name="accountKeyName">The name of the key used to create the signature, or <c>null</c> if the key is implicit.</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="delegationKey">Key information for signatures using user-delegation-based SAS.</param>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetSignature(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceType,
            string signature,
            string accountKeyName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            UserDelegationKey delegationKey = default(UserDelegationKey)
            )
        {
            CommonUtility.AssertNotNullOrEmpty("resourceType", resourceType);

            UriQueryBuilder builder = new UriQueryBuilder();

            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, sasVersion);
            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedResource, resourceType);
            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, accessPolicyIdentifier);
            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKey, accountKeyName);
            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature);
            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedProtocols, SharedAccessSignatureHelper.GetProtocolString(protocols));
            SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIP, ipAddressOrRange == null ? null : ipAddressOrRange.ToString());

            if (delegationKey != default(UserDelegationKey))
            {
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKeyOid, delegationKey.SignedOid.ToString());
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKeyTid, delegationKey.SignedTid.ToString());
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKeyStart, SharedAccessSignatureHelper.GetDateTimeOrNull(delegationKey.SignedStart));
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKeyExpiry, SharedAccessSignatureHelper.GetDateTimeOrNull(delegationKey.SignedExpiry));
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKeyService, delegationKey.SignedService);
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKeyVersion, delegationKey.SignedVersion);
            }

            if (policy != null)
            {
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, SharedAccessSignatureHelper.GetDateTimeOrNull(policy.SharedAccessStartTime));
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, SharedAccessSignatureHelper.GetDateTimeOrNull(policy.SharedAccessExpiryTime));

                string permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
                }
            }

            if (headers != null)
            {
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.CacheControl, headers.CacheControl);
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentType, headers.ContentType);
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentEncoding, headers.ContentEncoding);
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentLanguage, headers.ContentLanguage);
                SharedAccessSignatureHelper.AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentDisposition, headers.ContentDisposition);
            }

            return(builder);
        }
예제 #6
0
        /// <summary>
        /// Converts the specified value to either a string representation or <c>null</c>.
        /// </summary>
        /// <param name="protocols">The protocols to convert</param>
        /// <returns>A string representing the specified value.</returns>
        internal static string GetProtocolString(SharedAccessProtocol?protocols)
        {
            if (!protocols.HasValue)
            {
                return(null);
            }

            return(protocols.Value == SharedAccessProtocol.HttpsOnly ? "https" : "https,http");
        }
예제 #7
0
        /// <summary>
        /// Create a blob SAS build from Blob Object
        /// </summary>
        public static AccountSasBuilder SetAccountSasBuilder(SharedAccessAccountServices Service,
                                                             SharedAccessAccountResourceTypes type,
                                                             string Permission             = null,
                                                             DateTime?StartTime            = null,
                                                             DateTime?ExpiryTime           = null,
                                                             string iPAddressOrRange       = null,
                                                             SharedAccessProtocol?Protocol = null,
                                                             string EncryptionScope        = null)
        {
            AccountSasBuilder sasBuilder = new AccountSasBuilder();

            sasBuilder.ResourceTypes = GetAccountSasResourceTypes(type);
            sasBuilder.Services      = GetAccountSasServices(Service);

            sasBuilder = SetAccountPermission(sasBuilder, Permission);
            if (StartTime != null)
            {
                sasBuilder.StartsOn = StartTime.Value.ToUniversalTime();
            }
            if (ExpiryTime != null)
            {
                sasBuilder.ExpiresOn = ExpiryTime.Value.ToUniversalTime();
            }
            else
            {
                if (sasBuilder.StartsOn != DateTimeOffset.MinValue && sasBuilder.StartsOn != null)
                {
                    sasBuilder.ExpiresOn = sasBuilder.StartsOn.AddHours(1).ToUniversalTime();
                }
                else
                {
                    sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                }
            }
            if (iPAddressOrRange != null)
            {
                sasBuilder.IPRange = Util.SetupIPAddressOrRangeForSASTrack2(iPAddressOrRange);
            }
            if (Protocol != null)
            {
                if (Protocol.Value == SharedAccessProtocol.HttpsOrHttp)
                {
                    sasBuilder.Protocol = SasProtocol.HttpsAndHttp;
                }
                else //HttpsOnly
                {
                    sasBuilder.Protocol = SasProtocol.Https;
                }
            }
            if (EncryptionScope != null)
            {
                sasBuilder.EncryptionScope = EncryptionScope;
            }
            return(sasBuilder);
        }
        /// <summary>
        /// Returns a shared access signature for the table.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="startPartitionKey">A string specifying the start partition key, or <c>null</c>.</param>
        /// <param name="startRowKey">A string specifying the start row key, or <c>null</c>.</param>
        /// <param name="endPartitionKey">A string specifying the end partition key, or <c>null</c>.</param>
        /// <param name="endRowKey">A string specifying the end row key, or <c>null</c>.</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>
        /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
        public string GetSharedAccessSignature(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            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;

#if ALL_SERVICES
            string signature = SharedAccessSignatureHelper.GetHash(
#else
            string signature = TableSharedAccessSignatureHelper.GetHash(
#endif
                policy,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                resourceName,
                OperationContext.StorageVersion ?? Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange,
                accountKey.KeyValue);
#if ALL_SERVICES
            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(
#else
            UriQueryBuilder builder = TableSharedAccessSignatureHelper.GetSignature(
#endif
                policy,
                this.Name,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                signature,
                accountKey.KeyName,
                OperationContext.StorageVersion ?? Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange);

            return(builder.ToString());
        }
예제 #9
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="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>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessQueuePolicy policy,
            string accessPolicyIdentifier,
            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 = SharedAccessQueuePolicy.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
            ////
            //// 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}",
                permissions,
                GetDateTimeOrEmpty(startTime),
                GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                GetProtocolString(protocols),
                sasVersion);

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

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
예제 #10
0
        private static void ValidateProtocol(
            SharedAccessProtocol?expectedProtocol,
            string protocol)
        {
            string protocolString = "https,http";

            if (null != expectedProtocol && SharedAccessProtocol.HttpsOrHttp != expectedProtocol)
            {
                protocolString = "https";
            }

            Test.Assert(string.Equals(protocol.Replace("%2C", ","), protocolString), "Protocol: {0} == {1}", protocolString, protocol);
        }
        /// <summary>
        /// Returns an user-delegation-based shared access signature for the container, with credentials solely based on the <see cref="UserDelegationKey"/> provided.
        /// </summary>
        /// <param name="delegationKey"><see cref="UserDelegationKey"/> for signing this SAS token.</param>
        /// <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 container accessed with this SAS.</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></returns>
        public string GetUserDelegationSharedAccessSignature(
            UserDelegationKey delegationKey,
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers   = default(SharedAccessBlobHeaders),
            SharedAccessProtocol?protocols    = default(SharedAccessProtocol?),
            IPAddressOrRange ipAddressOrRange = default(IPAddressOrRange))
        {
            string resourceName = this.GetSharedAccessCanonicalName();

            string          signature = BlobSharedAccessSignatureHelper.GetHash(policy, headers, resourceName, Constants.HeaderConstants.TargetStorageVersion, Constants.QueryConstants.ContainerResourceType, null /* snapshotTime */, protocols, ipAddressOrRange, delegationKey);
            UriQueryBuilder builder   = BlobSharedAccessSignatureHelper.GetSignature(policy, headers, null, Constants.QueryConstants.ContainerResourceType, signature, null, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, delegationKey);

            return(builder.ToString());
        }
예제 #12
0
        /// <summary>
        /// Converts the specified value to either a string representation or <c>null</c>.
        /// </summary>
        /// <param name="protocols">The protocols to convert</param>
        /// <returns>A string representing the specified value.</returns>
        internal static string GetProtocolString(SharedAccessProtocol?protocols)
        {
            if (!protocols.HasValue)
            {
                return(null);
            }

            if ((protocols.Value != SharedAccessProtocol.HttpsOnly) && (protocols.Value != SharedAccessProtocol.HttpsOrHttp))
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, SR.InvalidProtocolsInSAS, protocols.Value));
            }

            return(protocols.Value == SharedAccessProtocol.HttpsOnly ? "https" : "https,http");
        }
예제 #13
0
        public void CloudBlobSASSharedProtocolsQueryParamInvalid()
        {
            SharedAccessProtocol?  protocol = default(SharedAccessProtocol);
            SharedAccessBlobPolicy policy   = new SharedAccessBlobPolicy()
            {
                Permissions            = SharedAccessBlobPermissions.Read,
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
            };

            CloudBlobContainer container = GetRandomContainerReference();
            CloudBlockBlob     blockBlob = container.GetBlockBlobReference("bb");

            TestHelper.ExpectedException <ArgumentException>(
                () => blockBlob.GetSharedAccessSignature(policy, null /* headers */, null /* stored access policy ID */, protocol, null /* IP address or range */),
                "Creating a SAS should throw when using an invalid value for the Protocol enum.",
                String.Format(SR.InvalidProtocolsInSAS, protocol));
        }
예제 #14
0
        private static UriQueryBuilder GetSignature(
            SharedAccessFilePolicy policy,
            SharedAccessFileHeaders headers,
            string accessPolicyIdentifier,
            string resourceType,
            string signature,
            string accountKeyName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            AddEscapedIfNotNull(builder, SignedVersion, sasVersion);
            AddEscapedIfNotNull(builder, SignedResource, resourceType);
            AddEscapedIfNotNull(builder, SignedIdentifier, accessPolicyIdentifier);
            AddEscapedIfNotNull(builder, SignedKey, accountKeyName);
            AddEscapedIfNotNull(builder, Signature, signature);
            AddEscapedIfNotNull(builder, SignedProtocols, GetProtocolString(protocols));
            AddEscapedIfNotNull(builder, SignedIP, ipAddressOrRange == null ? null : ipAddressOrRange.ToString());

            if (policy != null)
            {
                AddEscapedIfNotNull(builder, SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime));
                AddEscapedIfNotNull(builder, SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime));

                string permissions = SharedAccessFilePolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    AddEscapedIfNotNull(builder, SignedPermissions, permissions);
                }
            }

            if (headers != null)
            {
                AddEscapedIfNotNull(builder, CacheControl, headers.CacheControl);
                AddEscapedIfNotNull(builder, ContentType, headers.ContentType);
                AddEscapedIfNotNull(builder, ContentEncoding, headers.ContentEncoding);
                AddEscapedIfNotNull(builder, ContentLanguage, headers.ContentLanguage);
                AddEscapedIfNotNull(builder, ContentDisposition, headers.ContentDisposition);
            }

            return(builder);
        }
예제 #15
0
 internal static string GetProtocolString(SharedAccessProtocol?protocols)
 {
     if (!protocols.HasValue)
     {
         return(null);
     }
     if (protocols.Value != SharedAccessProtocol.HttpsOnly && protocols.Value != SharedAccessProtocol.HttpsOrHttp)
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid value {0} for the SharedAccessProtocol parameter when creating a SharedAccessSignature.  Use 'null' if you do not wish to include a SharedAccessProtocol.", new object[1]
         {
             protocols.Value
         }));
     }
     if (protocols.Value == SharedAccessProtocol.HttpsOnly)
     {
         return("https");
     }
     return("https,http");
 }
        /// <summary>
        /// Create a blob SAS build from container Object
        /// </summary>
        public static BlobSasBuilder SetBlobSasBuilder_FromContainer(BlobContainerClient container,
                                                                     BlobSignedIdentifier signedIdentifier = null,
                                                                     string Permission             = null,
                                                                     DateTime?StartTime            = null,
                                                                     DateTime?ExpiryTime           = null,
                                                                     string iPAddressOrRange       = null,
                                                                     SharedAccessProtocol?Protocol = null)
        {
            BlobSasBuilder sasBuilder = SetBlobSasBuilder(container.Name,
                                                          null,
                                                          signedIdentifier,
                                                          Permission,
                                                          StartTime,
                                                          ExpiryTime,
                                                          iPAddressOrRange,
                                                          Protocol);

            return(sasBuilder);
        }
예제 #17
0
        public static string GetSharedAccessSignature(
            CloudFile file,
            SharedAccessFilePolicy policy,
            SharedAccessFileHeaders headers,
            string groupPolicyIdentifier,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            string targetStorageVersion)
        {
            if (!file.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.InvariantCulture, "CannotCreateSASWithoutAccountKey");
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = GetCanonicalName(file);
            string signature    = GetHash(
                policy,
                headers,
                groupPolicyIdentifier,
                resourceName,
                targetStorageVersion,
                protocols,
                ipAddressOrRange,
                file.ServiceClient.Credentials.ExportKey());

            UriQueryBuilder builder =
                GetSignature(
                    policy,
                    headers,
                    groupPolicyIdentifier,
                    "f",
                    signature,
                    null,
                    targetStorageVersion,
                    protocols,
                    ipAddressOrRange);

            return(builder.ToString());
        }
예제 #18
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 file 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>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessFilePolicy policy,
            SharedAccessFileHeaders headers,
            string accessPolicyIdentifier,
            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 = SharedAccessFilePolicy.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" +
            ////                     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}",
                permissions,
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(startTime),
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                SharedAccessSignatureHelper.GetProtocolString(protocols),
                sasVersion,
                cacheControl,
                contentDisposition,
                contentEncoding,
                contentLanguage,
                contentType);

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

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
예제 #19
0
        /// <summary>
        /// Returns a shared access signature for the file.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessFilePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessFileHeaders"/> object specifying optional header values to set for a file 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(SharedAccessFilePolicy policy, SharedAccessFileHeaders 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();
            StorageAccountKey accountKey   = this.ServiceClient.Credentials.Key;

            string          signature = FileSharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, accountKey.KeyValue);
            UriQueryBuilder builder   = FileSharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, "f", signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange);

            return(builder.ToString());
        }
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
예제 #21
0
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     return(this.failoverExecutor.Execute(x => x.GetSharedAccessSignature(policy, 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));
            }
        }
예제 #23
0
 public abstract string GetAzureStorageFileSasFromCmd(string shareName, string filePath, string policy, string permission = null,
                                                      DateTime?startTime = null, DateTime?expiryTime = null, bool fulluri = false, SharedAccessProtocol?protocol = null, string iPAddressOrRange = null);
예제 #24
0
        /// <summary>
        /// Returns a shared access signature for the container.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="groupPolicyIdentifier">A container-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(SharedAccessBlobPolicy 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;

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

            return(builder.ToString());
        }
예제 #25
0
        /// <summary>
        /// Create a blob SAS build from Blob Object
        /// </summary>
        public static BlobSasBuilder SetBlobSasBuilder(string containerName,
                                                       string blobName = null,
                                                       BlobSignedIdentifier signedIdentifier = null,
                                                       string Permission             = null,
                                                       DateTime?StartTime            = null,
                                                       DateTime?ExpiryTime           = null,
                                                       string iPAddressOrRange       = null,
                                                       SharedAccessProtocol?Protocol = null,
                                                       string EncryptionScope        = null)
        {
            BlobSasBuilder sasBuilder;

            if (signedIdentifier != null) // Use save access policy
            {
                sasBuilder = new BlobSasBuilder
                {
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    Identifier        = signedIdentifier.Id
                };

                if (StartTime != null)
                {
                    if (signedIdentifier.AccessPolicy.StartsOn != DateTimeOffset.MinValue && signedIdentifier.AccessPolicy.StartsOn != null)
                    {
                        throw new InvalidOperationException(Resources.SignedStartTimeMustBeOmitted);
                    }
                    else
                    {
                        sasBuilder.StartsOn = StartTime.Value.ToUniversalTime();
                    }
                }

                if (ExpiryTime != null)
                {
                    if (signedIdentifier.AccessPolicy.PolicyExpiresOn != DateTimeOffset.MinValue && signedIdentifier.AccessPolicy.PolicyExpiresOn != null)
                    {
                        throw new ArgumentException(Resources.SignedExpiryTimeMustBeOmitted);
                    }
                    else
                    {
                        sasBuilder.ExpiresOn = ExpiryTime.Value.ToUniversalTime();
                    }
                }
                else if (signedIdentifier.AccessPolicy.PolicyExpiresOn == DateTimeOffset.MinValue && signedIdentifier.AccessPolicy.PolicyExpiresOn != null)
                {
                    if (sasBuilder.StartsOn != DateTimeOffset.MinValue && sasBuilder.StartsOn != null)
                    {
                        sasBuilder.ExpiresOn = sasBuilder.StartsOn.ToUniversalTime().AddHours(1);
                    }
                    else
                    {
                        sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                    }
                }

                if (Permission != null)
                {
                    if (signedIdentifier.AccessPolicy.Permissions != null)
                    {
                        throw new ArgumentException(Resources.SignedPermissionsMustBeOmitted);
                    }
                    else
                    {
                        sasBuilder = SetBlobPermission(sasBuilder, Permission);
                    }
                }
            }
            else // use user input permission, starton, expireon
            {
                sasBuilder = new BlobSasBuilder
                {
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                };
                sasBuilder = SetBlobPermission(sasBuilder, Permission);
                if (StartTime != null)
                {
                    sasBuilder.StartsOn = StartTime.Value.ToUniversalTime();
                }
                if (ExpiryTime != null)
                {
                    sasBuilder.ExpiresOn = ExpiryTime.Value.ToUniversalTime();
                }
                else
                {
                    if (sasBuilder.StartsOn != DateTimeOffset.MinValue)
                    {
                        sasBuilder.ExpiresOn = sasBuilder.StartsOn.AddHours(1).ToUniversalTime();
                    }
                    else
                    {
                        sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                    }
                }
            }
            if (iPAddressOrRange != null)
            {
                sasBuilder.IPRange = Util.SetupIPAddressOrRangeForSASTrack2(iPAddressOrRange);
            }
            if (Protocol != null)
            {
                if (Protocol.Value == SharedAccessProtocol.HttpsOrHttp)
                {
                    sasBuilder.Protocol = SasProtocol.HttpsAndHttp;
                }
                else //HttpsOnly
                {
                    sasBuilder.Protocol = SasProtocol.Https;
                }
            }
            if (EncryptionScope != null)
            {
                sasBuilder.EncryptionScope = EncryptionScope;
            }
            return(sasBuilder);
        }
예제 #26
0
 public virtual string GetTableSasFromCmd(string tableName, string policy, string permission,
                                          DateTime?startTime = null, DateTime?expiryTime = null, bool fulluri = false,
                                          string startpk     = "", string startrk        = "", string endpk = "", string endrk = "", SharedAccessProtocol?protocol = null, string iPAddressOrRange = null)
 {
     return(string.Empty);
 }
예제 #27
0
 public virtual string GetAccountSasFromCmd(SharedAccessAccountServices service, SharedAccessAccountResourceTypes resourceType, string permission, SharedAccessProtocol?protocol, string iPAddressOrRange,
                                            DateTime?startTime = null, DateTime?expiryTime = null)
 {
     return(string.Empty);
 }
        /// <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));
        }
예제 #29
0
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, SharedAccessProtocol?protocols = null, IPAddressOrRange ipAddressOrRange = null)
 {
     return(_queue.GetSharedAccessSignature(policy, accessPolicyIdentifier, protocols, ipAddressOrRange));
 }
예제 #30
0
 public abstract bool NewAzureStorageFileSAS(CloudFile file, string policyName = null, string permissions = null,
                                             DateTime?startTime = null, DateTime?expiryTime = null, bool fulluri = false, SharedAccessProtocol?protocol = null, string iPAddressOrRange = null);