Skip to main content

Demystify how Shared Access Signature (SAS) is created inside Azure Storage

In this post, we will take a look on how Shared Access Signature (SAS) is generated. We would like to understand:
  • How such a signature is generated
  • What are the inputs that are required for it 
  • What does the signature contains
I assume that you have base the knowledge’s related to SAS. If not I would recommend to read the following introduction before - https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1

What does the SAS signature token contains?
This signature (token) is just a specific HMAC (keyed-hash message authentication code) generated using SHA256 hashing algorithm. There is no magic behind it. Inside this token all the relevant information related to access permissions, expiration date and many more are ‘hashed’.
By ‘hashed’ I understand a hash that is generated from the string that contains in clear text all the information related to SAS together with storage account key.
For example, for the below SAS string
1
SAS String = sv=2017-12-21&se=2017-12-28T00%3A12%3A08Z&sr=c&sp=wl

hashed using as key the Azure Storage account key the function call would look like something like this:
1
SAS Signature = HMAC ( SHA256 ( SAS String , Azure Storage Account Key ) )

As we can see, there is no magic behind it. On Azure Storage backend the SAS signature is recreated when you make a request and is checked against the one that you provided. If there is full match then your access is granted. 
I so many times people assuming that inside the SAS signature all the policies and rights are hidden. No, this is false, it's just a simple signature. In this way the system is more simple and safer.
Using this approach there is the ability to invalidated all the SAS that were generated by recreating a new Azure Storage Account Key - simple and clean.

When a new SAS signature is created, do I need to make a call to Azure Storage?
No, there is no need to make a behind the scene to Azure Storage API. All the information required to generated the SAS signature are already available on the machine. This means that we can generate as many SAS access keys we want directly from our machine.
A good example is the below SAS signature implementation written in JavaScript.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function generateSignature(base64EncodedSharedKey, startTime, endTime, account, container, blobName) {  
   var stringToSign = "rn{0}n{1}n/{2}/{3}/{4}n"  
      .replace(/{0}/, startTime.toIso8061())  
      .replace(/{1}/, endTime.toIso8061())  
      .replace(/{2}/, account)  
      .replace(/{3}/, container)  
      .replace(/{4}/, blobName);  
   var accessKeyBytes = Crypto.util.base64ToBytes(base64EncodedSharedKey);  
   return Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA256, stringToSign, accessKeyBytes, { asBytes: true }));  
} 
Let us start from the beginning and understand what does the SAS signature is when is generated from a SAP contains and the base purpose.

The biggest difference between SAP and a standard SAS is the way in which you manage the SAP. Once a new policy is defined you need to assign it to a specific Azure Storage resource (e.g. to an Azure Storage Container).
The access level and other details that you specify at this level are ‘kept’ inside Azure Storage on that specific policy. This is giving us the ability to specify at policy level what are the rights for that policy and generate an unlimited number of Shared Access Signatures for it.This means that in the moment when you define a policy and attach it to Azure Storage resource, an HTTP/S call is made to Azure Storage to persist it. 

One of the main advantage of access policy is the ability to change the access level or other details like validity period even after you generated and shared the SAS of that policy.  You can refer any time a specific policy using the policy name.
For example, you can decide to extend the validity of the policy and extend it with one more year. This would require only to load the policy from Azure Storage for that specific resource and update the expiration time. No SAS tokens regeneration on top of that policy are required.

Because the Azure Storage Account Key it is used when policies and SAS for specific policies are created, by invaliding an account key, all the SAS that were generated using that account key for policies will be invalided. BUT without invalidating/deleting the policy itself. This means that you can created new SAS for existing policies using the new account key.

Remarks: There is a limit of maximum five policies that can be defined per resource (e.g. Azure Storage Container, Azure Table Partition).

One more thing, in comparison with a standard SAS query string, the one that is created on top of a policy will contain the signature, but without the parameters. The parameters are already stored inside the policy (that is kept on backend side - Azure Storage)


1
?sv=2017-04-17&si=AccountName&sr=c&sig=q%2B0DD2jYHXDH3YxKMggQ57uWYMyh5iL%2Be1msWRwjQo8%3D

Conclusion
As we can see, SAS signature is nothing more than a hash. Even if the mechanism is simple, it's powerful and gives us the ability to share access to a specific resources without doing complex steps. SAP allows us to control and change the rights in a more controlled manner. 

Comments

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Fundamental Books of a Software Engineer (version 2018)

More then six years ago I wrote a blog post about fundamental books that any software engineer (developer) should read. Now it is an excellent time to update this list with new entries.

There are 5 different categories of books, that represent the recommended path. For example, you start with Coding books, after that, you read books about Programming, Design and so on.
There are some books about C++ that I recommend not because you shall know C++, only because the concepts that you can learn from it.

Coding

Writing solid codeCode completeProgramming Pearls, more programming pearls(recommended)[NEW] Introduction to Algorithms

Programming

Refactoring (M. Fowler)Pragmatic ProgrammerClean code[NEW] Software Engineering: A Practitioner's Approach[NEW] The Mythical Man-Month[NEW] The Art of Computer Programming

Design

Applying UML and Patterns (GRASP patterns)C++ coding standards (Sutter, Alexandrescu)The C++ programming language (Stroustrup, Part IV)Object-oriented programming (Peter Coad)P…

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…