protected override async Task <SecretData> RotateValue(Parameters parameters, RotationContext context, CancellationToken cancellationToken)
        {
            DateTimeOffset      now        = _clock.UtcNow;
            CloudStorageAccount account    = CloudStorageAccount.Parse(await context.GetSecretValue(parameters.ConnectionString));
            CloudBlobClient     blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer  container  = blobClient.GetContainerReference(parameters.Container);
            CloudBlob           blob       = container.GetBlobReference(parameters.Blob);
            string sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
            {
                Permissions            = SharedAccessBlobPolicy.PermissionsFromString(parameters.Permissions),
                SharedAccessExpiryTime = now.AddMonths(1),
            });
            string result = blob.Uri.AbsoluteUri + sas;

            return(new SecretData(result, now.AddMonths(1), now.AddDays(15)));
        }
Exemple #2
0
        /// This method obtains a SAS URL for the Storage container provided in ExportParams class
        /// As an alternative you may pass this URL as a command line parameter, using the documentation at https://docs.microsoft.com/en-us/azure/vs-azure-tools-storage-explorer-blobs#get-the-sas-for-a-blob-container
        private static string getStorageUrlWithSas()
        {
            string             storageUri = $"https://{ExportParams.azureStorageAccountName}.blob.core.windows.net/{ExportParams.azureStorageContainerName}";
            CloudBlobContainer container  = new CloudBlobContainer(
                new Uri(storageUri),
                new StorageCredentials(ExportParams.azureStorageAccountName, ExportParams.azureStorageAccountKey)
                );
            SharedAccessBlobPolicy sasPolicy = new SharedAccessBlobPolicy();

            // Require permission Write and List
            sasPolicy.Permissions = SharedAccessBlobPolicy.PermissionsFromString("wl");
            //
            sasPolicy.SharedAccessExpiryTime = DateTimeOffset.Now.AddDays(1);
            sasPolicy.SharedAccessStartTime  = DateTimeOffset.Now;
            String sas = container.GetSharedAccessSignature(sasPolicy);

            return(storageUri + sas);
        }
        public string GetBlobContainerSasToken(string accountName, string containerName, string permissions, DateTimeOffset expiryDateTimeOffset)
        {
            var        accessToken = GetStorageSasToken();
            UriBuilder sasUri      = new UriBuilder()
            {
                Scheme = "https",
                Host   = $"{accountName}.blob.core.windows.net",
                Query  = accessToken
            };
            var blobClient      = new CloudBlobClient(sasUri.Uri);
            var containerRef    = blobClient.GetContainerReference(containerName);
            var permissionsEnum = SharedAccessBlobPolicy.PermissionsFromString(permissions);
            var token           = containerRef.GetSharedAccessSignature(new SharedAccessBlobPolicy
            {
                Permissions            = permissionsEnum,
                SharedAccessExpiryTime = expiryDateTimeOffset,
            });

            return(token);
        }
Exemple #4
0
 internal static void SetupAccessPolicyPermission <T>(T policy, string permission)
 {
     //set permission as none if passed-in value is empty
     if (permission == null)
     {
         return;
     }
     if (string.IsNullOrEmpty(permission))
     {
         if (typeof(T) == typeof(SharedAccessTablePolicy))
         {
             ((SharedAccessTablePolicy)(Object)policy).Permissions = SharedAccessTablePermissions.None;
         }
         else if (typeof(T) == typeof(SharedAccessFilePolicy))
         {
             ((SharedAccessFilePolicy)(Object)policy).Permissions = SharedAccessFilePermissions.None;
         }
         else if (typeof(T) == typeof(SharedAccessBlobPolicy))
         {
             ((SharedAccessBlobPolicy)(Object)policy).Permissions = SharedAccessBlobPermissions.None;
         }
         else if ((typeof(T) == typeof(SharedAccessQueuePolicy)))
         {
             ((SharedAccessQueuePolicy)(Object)policy).Permissions = SharedAccessQueuePermissions.None;
         }
         else
         {
             throw new ArgumentException(Resources.InvalidAccessPolicyType);
         }
         return;
     }
     permission = permission.ToLower(CultureInfo.InvariantCulture);
     try
     {
         if (typeof(T) == typeof(SharedAccessTablePolicy))
         {
             //PowerShell will convert q to r in genreate table SAS. Add this to avoid regression
             string convertedPermission = permission.Replace('q', 'r');
             ((SharedAccessTablePolicy)(Object)policy).Permissions = SharedAccessTablePolicy.PermissionsFromString(convertedPermission);
         }
         else if (typeof(T) == typeof(SharedAccessFilePolicy))
         {
             ((SharedAccessFilePolicy)(Object)policy).Permissions = SharedAccessFilePolicy.PermissionsFromString(permission);
         }
         else if (typeof(T) == typeof(SharedAccessBlobPolicy))
         {
             ((SharedAccessBlobPolicy)(Object)policy).Permissions = SharedAccessBlobPolicy.PermissionsFromString(permission);
         }
         else if ((typeof(T) == typeof(SharedAccessQueuePolicy)))
         {
             ((SharedAccessQueuePolicy)(Object)policy).Permissions = SharedAccessQueuePolicy.PermissionsFromString(permission);
         }
         else
         {
             throw new ArgumentException(Resources.InvalidAccessPolicyType);
         }
     }
     catch (System.ArgumentOutOfRangeException)
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.InvalidAccessPermission, permission));
     }
 }
Exemple #5
0
        public static async Task <bool> IsAuthorizedAsync(IHttpRequestWrapper request, RequestHeaders headers, RequestQueryParameters queryParams, bool ignoreRequestAge)
        {
            var            requestUriParts = request.UriParts;
            var            resourceType    = queryParams.Value <string>(ParamResourceType, String.Empty).ToLowerInvariant();
            DateTimeOffset?start           = queryParams.Value(ParamStartTime, DateTimeOffset.UtcNow);
            DateTimeOffset?expiry          = queryParams.Value(ParamExpiryTime, DateTimeOffset.MinValue);

            if (expiry == DateTimeOffset.MinValue)
            {
                expiry = null;
            }
            SharedAccessBlobPermissions permissions = SharedAccessBlobPolicy.PermissionsFromString(queryParams.Value(ParamPermissions, String.Empty));

            // Determine validity of the structure first
            if (requestUriParts.IsAccountRequest)
            {
                // SAS keys are not valid for account operations
                return(false);
            }
            else if (requestUriParts.IsContainerRequest && resourceType != "c")
            {
                return(false);
            }
            else if (requestUriParts.IsBlobRequest && resourceType.IndexOfAny(new [] { 'c', 'b' }) == -1)
            {
                return(false);
            }
            var storedPolicyId = queryParams.Value <string>(ParamStoredPolicy);

            if (!String.IsNullOrWhiteSpace(storedPolicyId))
            {
                // Validate that we're not duplicating values for both stored access policy & url
                var storedPolicy = await GetStoredPolicyForContainer(requestUriParts.Container, storedPolicyId);

                if (storedPolicy == null)
                {
                    return(false);
                }
                if (storedPolicy.SharedAccessStartTime.HasValue)
                {
                    start = storedPolicy.SharedAccessStartTime;
                }
                if (storedPolicy.SharedAccessExpiryTime.HasValue)
                {
                    if (expiry.HasValue)
                    {
                        return(false);
                    }
                    expiry = storedPolicy.SharedAccessExpiryTime;
                }
                if (queryParams.Contains(ParamPermissions))
                {
                    return(false);
                }
                permissions = storedPolicy.Permissions;
            }
            if (!expiry.HasValue || permissions == SharedAccessBlobPermissions.None)
            {
                return(false);
            }
            else if (!ignoreRequestAge && (start.Value > DateTimeOffset.UtcNow || expiry.Value < DateTimeOffset.UtcNow))
            {
                return(false);
            }
            // Verify the assigned permissions line up with the requested operation
            StorageOperationTypes requestOperation = StorageOperations.GetBlobOperation(request);

            switch (requestOperation)
            {
            case StorageOperationTypes.GetBlob:
            case StorageOperationTypes.GetBlobMetadata:
            case StorageOperationTypes.GetBlobProperties:
            case StorageOperationTypes.GetBlockList:
            case StorageOperationTypes.GetPageRanges:
                if (!permissions.IsFlagSet(SharedAccessBlobPermissions.Read))
                {
                    return(false);
                }
                break;

            case StorageOperationTypes.AbortCopyBlob:
            case StorageOperationTypes.CopyBlob:
            case StorageOperationTypes.LeaseBlob:
            case StorageOperationTypes.PutBlob:
            case StorageOperationTypes.PutBlock:
            case StorageOperationTypes.PutBlockList:
            case StorageOperationTypes.PutPage:
            case StorageOperationTypes.SetBlobMetadata:
            case StorageOperationTypes.SetBlobProperties:
            case StorageOperationTypes.SnapshotBlob:
                if (!permissions.IsFlagSet(SharedAccessBlobPermissions.Write))
                {
                    return(false);
                }
                break;

            case StorageOperationTypes.DeleteBlob:
                if (!permissions.IsFlagSet(SharedAccessBlobPermissions.Delete))
                {
                    return(false);
                }
                break;

            case StorageOperationTypes.ListBlobs:
                if (!permissions.IsFlagSet(SharedAccessBlobPermissions.List))
                {
                    return(false);
                }
                break;

            default:
                // All other operations are not supported by SAS uris
                return(false);
            }
            DateTimeOffset sasVersion          = queryParams.Value(ParamVersion, StorageServiceVersions.Version_2009_09_19);
            Func <string>  stringToSignFactory = null;
            Func <string>  baseStringToSign    = () => String.Format("{0}\n{1}\n{2}\n{3}\n{4}",
                                                                     queryParams.Value <string>(ParamPermissions),
                                                                     queryParams.Value <string>(ParamStartTime),
                                                                     queryParams.Value <string>(ParamExpiryTime),
                                                                     GetCanonicalizedResource(requestUriParts, resourceType),
                                                                     queryParams.Value <string>(ParamStoredPolicy));
            Func <string> v2012_02_12StringToSign = () => String.Format("{0}\n{1}",
                                                                        baseStringToSign(),
                                                                        queryParams.Value <string>(ParamVersion));

            if (sasVersion < StorageServiceVersions.Version_2012_02_12)
            {
                stringToSignFactory = baseStringToSign;
            }
            else if (sasVersion == StorageServiceVersions.Version_2012_02_12)
            {
                stringToSignFactory = v2012_02_12StringToSign;
            }
            else
            {
                stringToSignFactory = () => String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
                                                          v2012_02_12StringToSign(),
                                                          queryParams.Value <string>(ParamCacheControl),
                                                          queryParams.Value <string>(ParamContentDisposition),
                                                          queryParams.Value <string>(ParamContentEncoding),
                                                          queryParams.Value <string>(ParamContentLang),
                                                          queryParams.Value <string>(ParamContentType));
            }
            string signature       = queryParams.Value <string>(ParamSignature);
            var    usingPrimaryKey = new[] { true, false };
            int    matchIndex      = Array.FindIndex(usingPrimaryKey, usePrimaryKey => VerifySignature(signature, usePrimaryKey, stringToSignFactory));

            if (matchIndex != -1)
            {
                // We can't sign the redirection response when the request uses a SAS key - preserve the matching key, however
                request.AuthenticationScheme = String.Empty;
                request.AuthenticationKey    = usingPrimaryKey[matchIndex] ? SharedKeySignature.PrimaryAccountKey : SharedKeySignature.SecondaryAccountKey;
                return(true);
            }
            return(false);
        }