Monday, December 17, 2018

Two-Factor authentication with Azure sphere and Azure IoT hub - Step by step

Introduction


The story began in my previous post Two-Factor authentication with Azure sphere and Azure IoT hub where I introduced the idea of using Azure sphere and Azure IoT to create a two factor authentication solution. In this post, we will look deep into the technical details of implementation. This is a little longer blog post. I have tried my best to make it as simple to understand and follow as it is possible. I start off by given out the high-level architecture mentioned in my previous blog post and then the technical architecture that is the technical evolution of the high-level architecture. Then I start with how the authenticator application will carry out two factor authentication. I show the screens so that it is easier to grasp the technical details that will follow. Then we take a look at the key components of the technical implementation of two-factor authentication with Azure Sphere and Azure IoT hub. At the last section, we will take a look at the step by step flow of the technical details.

If you have any questions or need any details on part of this implementation, please feel free to contact me at: mnabeelkhan@gmail.com

Prerequisites

  1. Since Two-Factor Authentication using Azure Sphere is based on Azure Sphere device connected to user's machine, it is important to mention that the prerequisite of this system is to have Azure Sphere device properly connected the user's machine. Information on setting up Azure Sphere device with a machine is provide in previous blog post Getting started with Azure Sphere
  2. The second prerequisite is to make sure the Azure Sphere device has been added to an Azure IoT hub. More information for that can be found at Microsoft Docs article Set up an IoT Hub for Azure Sphere
  3. The final prerequisite is that the Azure Sphere device has a deployed version of the code that is part of the Two-Factor authentication. The last section before the conclusion mentions the code that is needed for the Azure Sphere part of the solution under the heading Azure Sphere - main.c code.

Let us start by taking a look at the high-level architecture design for presented in the post  Two-Factor authentication with Azure sphere and Azure IoT hub
Figure 1 - High-level architecture


Taking the high-level architecture forward, the evolved technical architecture is created as shown below:
Figure 2 - Technical Architecture

Before taking a detailed look at the technical architecture, let us start with looking at how the Authenticator application will work. This will give a good overview of what we are building (in terms of the end goal) and it will make it easier for us to understand the technical details.


User Interaction Flow

This sections illustrates the step by step interaction of user with the authenticator using screen shots.

1. Login page to initiate the first factor authentication
Figure 3 - Login screen

This step is quite simple. The above screen just carries out the first factor authentication.


2. User enters the user name and password for first factor authentication
Figure 4 - Login screen with user input






3. After successful first factor authentication, user is presented with a page to complete the second factor as show below:
Figure 5 - Second factor authentication screen showing status as "Pending"



4. As instructed in the Second factor authentication page, user presses the button "B" on the Azure Sphere device and the clicks the "Validate Second Factor" button on the screen.


5. As the result the authenticator validates the second factor and shows the authentication result as show below:
Figure 6 - Second factor authentication screen showing status as "true" (authenticated)

Now we have seen how the Authenticator application will look like and how it will interact with user, let delve into key components of the Two-Factor authentication using Azure Sphere and Azure IoT hub.

Key Components

User

User is initiator and the requester of the two factor authentication. It represents the user using a machine or device that is connected to Azure Sphere. The prerequisite section of the post Two-Factor authentication with Azure sphere and Azure IoT hub mentions the essential prerequisites for the user. 

Azure Sphere

This is the device that is attached to the user machine. It is responsible for second factor authentication. The request are received by the Azure Sphere by the Azure IoT hub and based on the request, it creates the security code that constitutes the essential part of the second factor authentication.

Authenticator

This represents the application that needs carries out the Two-Factor authentication. This can be a web app or an API. The authenticator acts as the controller of the Two-Factor authentication system by coordinating the calls that are requesting for first factor or second factor authentication. It talks to Azure Table Storage and sends requests in form of notifications to IoT hub when it needs to talk to Azure Sphere.

Azure IoT hub

Azure IoT hub is the central point of contact for requests and responses that are received to complete the second factor authentication. The Azure IoT hub receives the requests from the Azure Sphere device and forwards it as an event notification. The event notifications are then consumed by the Azure functions for processing. As mentioned in the prerequisite section of  Two-Factor authentication with Azure sphere and Azure IoT hub the Azure Sphere device has to be provisioned with Azure IoT hub.

Azure Table Storage

Azure table storage acts as the backing store for all the requests. When authenticator receives a requests, it creates a record in the TwoFactorRequest table which constitutes the Azure table storage. When Azure Sphere creates the security code, the security code is saved in the TwoFactorRequest table under the column "CreatedSecurityCode". When Azure Sphere retrieves the security code from its mutable memory, it is stored under the column "RetreivedSecurityCode". The authenticator uses these two columns to validate if the user has completed the second factor authentication or not.
Let us take a look at the structure of TwoFactorRequest Azure table storage.
Figure 7 - TwoFactorRequest table structure


Here is a quick view of the TwoFactoRequest table structure.
Figure 8 - Azure table storage quick view








Azure Function

There are two Azure Functions created for this solution. These are "Recorder" Azure function and "Validator" Azure function. The primary purpose of the these two Azure Functions is to receive notification for Azure IoT hub and post the results to Azure table storage in the TwoFactorRequest table. These Azure functions uses the built-in endpoints in Azure IoT hub to hook into event notifications. More detail on how to use built-in endpoints can be found on my previous blog post Leveraging Built-in endpoints in Azure IoT Hub
Although the architecture proposes to two use two separate function, we can use one function to be consumer of all the events and based on the request type, it can route to functions that will fulfill the tasks of either the "Recorder" or "Validator" functions. 

Here is the code snippet for the Azure function

Let us take a look at the code real quick. The Azure function is represented in form of static class called "DeviceMessageRecorderFunction". This class listens to event hub triggers by the user of its "Run" method. In the "Run" method the Azure Function looks at the message that it received from the Azure IoT hub. As mentioned the Azure IoT hub sends the event notification for two times. These are when the security code is created and when the security code is retrieved for validation. The Azure IoT sends these event notification messages as a result of being invoked by the Azure Sphere. For these two events, the message body is different. The message is "|" separated string.

When the security code is generated by the Azure Sphere it posts the message to Azure IoT hub in the following format.

Message format: userName|uniqueId|correlationId

Message example: admin|d6c28aef-8da6-4678-806d-2634b30266fc|e386a74be1ef4795a41432f2d59f8136

When the security code is retrieved for validation, the Azure Sphere sends the message to IoT hub in the following format

Message format: userName|uniqueId|correlationId|securityCode

Message example: admin|d6c28aef-8da6-4678-806d-2634b30266fc|e386a74be1ef4795a41432f2d59f8136|32322|retrieved

Going back to the "Run" method code, the code checks for the method type and based on its type it enters the data in the Azure table storage. This method takes care of both "Recorder" and "Validator" functionality.

Step by step flow

Let us take another look at the technical architecture:

Figure 9 - Technical Architecture

Let us take a look at the technical architecture in detail in terms of steps.

  1. The user sends the first factor authentication request in form of the user name and password as a secured post request.
  2. The authenticator validates the user name and password request thus completing the first factor authentication.
  3. In this step the authenticator creates a record in the TwoFactorRequest Azure table storage. It will have both "CreateSecurityCode" and "RetrievedSecurityCode" fields as null. This represents that a new request is going to go through the second factor authentication.
    Here is the code that that creates a new record in the TwoFactorRequest Azure table
  4. After creating a new request in TwoFactorRequest table, the authenticator sends a message to Azure IoT to request the Azure Sphere device to create a new "SecurityCode" using direct method to Azure Sphere.

    Here is the message format that is sent to Azure Sphere through Azure IoT.
    Message format: userName|uniqueId|correlationId

    Message example: admin|d6c28aef-8da6-4678-806d-2634b30266fc|e386a74be1ef4795a41432f2d59f8136

    Here is the code that invokes a direct method to Azure Sphere through Azure IoT:

  5. As a result of the "DirectMethod" invocation, the Azure Sphere device generates a "Security Code" for second factor authentication. 
  6. Azure Sphere device then saves the created "Security Code" in its mutable memory and notifies the Azure IoT. The message that is sent to Azure IoT from Azure Sphere is show below:
    Message format: userName|uniqueId|correlationId|securityCode

    Message example: admin|d6c28aef-8da6-4678-806d-2634b30266fc|e386a74be1ef4795a41432f2d59f8136|2123

    In the above message the last segment "2123" represents the security code created
  7. Message is forwarded by the Azure IoT to Recorder function that is listening to events coming out of Azure IoT hub. The code mentioned in the section under "Azure Functions" takes care of that.
  8. The Azure function then updates the TwoFactorRequest table with the "SecurityCode" received from Azure Sphere through Azure IoT hub.
  9. As part of the Two-Factor authentication flow, the user has to press the button "B" on the Azure Sphere device. This ensures the user has access to the Azure Sphere device and the Azure Sphere device is properly provisioned with Azure IoT hub.
  10. Once user presses the button "B" on the Azure Sphere device, the Azure Sphere device retrieves the "Security Code" as the second factor from its mutable memory and posts it Azure IoT hub.
    For this step, the message that is sent to Azure IoT hub is in the following format:


    Message format: userName|uniqueId|correlationId|securityCode|retrieved


    Message example: admin|d6c28aef-8da6-4678-806d-2634b30266fc|e386a74be1ef4795a41432f2d59f8136|32322|retrieved
  11. The Azure IoT hub receives the retrieved message for validation and generates an event hub notification. This event hub notification is received by the Azure function. The code mentioned in the section under "Azure Functions" takes care of that.
  12. The Azure Function then validates that the security code that is retrieved is same when the first time Azure Sphere sent message as part of step 6.
  13. The Azure Function, then updates the TwoFactorRequest table with the retrieved "Security Code".

Once all the steps are completed and the security code is verified to be the same, the authenticator then notifies the user of successful authentication.


Azure Sphere's main.c code


Conclusion

In this blog post, we have seen how to implement Two-Factor authentication using Azure Sphere and Azure IoT hub. We have started off with the user interaction screens to have an overview of what we are building. Then we looked deeply in each key component of this system. After that the steps help us explain the technical architecture in detail.

If you have any questions or need any details on part of this implementation, please feel free to contact me at: mnabeelkhan@gmail.com


Friday, December 7, 2018

How to read appSettings JSON from Class Library in ASP.NET Core without modifying the Class Library

Back story

I recently ran into an issue where I needed to read the settings from ASP.NET Core app into a Class Library project. Since I was creating the ASP.NET Core, I had the access to the source code. But the class library was already written and I had no access to source code and hence any change that I was suppose to do had to be done in the ASP.NET Core app.




I looked for solution and found one here : https://corderoski.wordpress.com/2017/09/18/how-to-read-appsettings-json-from-class-library-in-asp-net-core/

The solution was great as long as you have the ability to change both the ASP.NET Core app and the Class Library. Since I did not have the access to source code for the Class Library, I could not use that solution.

So I came up with following solution.

Solution


On the constructor of the ASP.NET Core app, I added the following code:

        public MyController(IConfiguration configuration)
        {
            this.configuration = configuration;
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);

            // Remove previous settings to ensure new settings are applied.
            if(settings[Settings1Key] != null)
            {
                settings.Remove(Settings1Key);
            }
            if (settings[Settings2Key] != null)
            {
                settings.Remove(Settings2Key);
            }
            if (settings[Settings3Key] != null)
            {
                settings.Remove(Settings3Key);
            }

            settings.Add("Settings1Key", this.configuration["Settings1Key"]);
            settings.Add("Settings2Key", this.configuration["Settings2Key"]);
            settings.Add("Settings3Key", this.configuration["Settings3Key"]);
            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
        }

Here the code change that I made to the Startup.cs file in the ASP.NET Core app:


        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton(Configuration);
        }


That is it. What we have done here is that we pulled the settings from the appsettings.json file on run time and modified the ConfigurationManager on runtime and saved it. Now when the Class Library is called, it had the access to the configuration that it was looking for.

Happy coding!


Tuesday, December 4, 2018

Two-Factor authentication with Azure sphere and Azure IoT hub

Introduction

This blog post introduces to a new way of carrying out two factor authentication using Azure Sphere. As more and more devices are being added to IoT world, there has been increasing need for a device that is secure and connects to Azure IoT to further automate the process. Azure Sphere fills that gap of secure communication. More information on Azure Sphere can be found at: https://azure.microsoft.com/en-us/blog/introducing-microsoft-azure-sphere-secure-and-power-the-intelligent-edge/

The intended goal of this blog post is to present a use of Azure Sphere. The best way to understand any technology is by creating a product or use that shows how the technology works and how it can be leveraged. This blog post presents a use of Azure Sphere by introducing a way to implement "Two factor authentication".

Information on how to setup Azure Sphere can be found in my previous blog post at: Getting started with Azure Sphere


Disclaimers

The information provided in this blog is intended to demonstrate a novel use of Azure Sphere. It does not recommend the "Azure Sphere based two factor Authentication" be used in production environment. The recommendation is to use the material provided in this blog as an opportunity to learn and understand Azure Sphere and Azure IoT.

Typical two factor authentication

Let us start by looking a typical two factor authentication. In traditional two factor authentication, a user (using a supported device like, smart phone, desktop or tablet), initiates the authentication by providing a user name and password to the authentication provider. Typically an authentication provider is the system that is part of a web site or an application. The authentication provider takes the user name and password and authenticates the user. This user of user name and password constitutes the first factor of the authentication. On successful authentication of the first factor (user name and password), the authentication provider sends a code to device that is associated with the user who is requesting the authentication. Typically the code sent through text or a phone call. The user receives the code. The authentication provider then provides a page for the user to enter the code that is sent. This code constitutes what we call the second factor. On receiving the second factor (code) the authentication provider verifies the code and completes the authentication process. 
Following diagram illustrates the typical two factor authentication flow.

Figure 1 - Typical two factor authentication flow

Two-Factor Authentication using Azure Sphere

The Two-Factor Authentication using Azure Sphere uses the same authentication mechanism for the first factor (i.e. username and password). But for the second factor it leverages the Azure Sphere device. The Azure Sphere device is attached to a device that is being used by the user requesting the authentication. This replaces the need to have the authentication provider send a code to a user device (such as phone for text message). Instead it relies on the Azure Sphere attached a users device to carryout the second factor authentication. The Azure Sphere device is connected to Azure IoT and that communication is secured by design.
The inspiration of using Azure Sphere as the second factor authentication device came from a paper called "The Seven Properties of Highly Secure Devices" published by Galen Hunt, George Letey, and Edmund B. Nightingale of Microsoft Research. Here is the link for that paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2017/03/SevenPropertiesofHighlySecureDevices.pdf

Why use Azure Sphere for second factor authentication


  1. Hardware based security. As mentioned in the "The Seven Properties of Highly Secure Devices" paper, the "Highly secure devices have a hardware-based root of trust." Here is the excerpt from that paper.
    Highly secure devices have a hardware-based root of trust. Device secrets are protected by hardware and the hardware contains physical countermeasures against side-channel attacks. Unlike software, hardware has two important properties that may be used to establish device security. First, single purpose hardware is immune to reuse by an attacker for unintended actions. Second, hardware can detect and mitigate against physical attacks; for example, pulse testing the reset pin to prevent glitching attacks is easily implemented in hardware. When used to protect secrets and device correctness, hardware provides a solid root of trust upon which rich software functionality can be implemented securely and safely. 
  2. Secured Communication: The communication between the Azure Sphere device and Azure IoT hub is secured by Azure. As system implementor we would not need to secure the communication as we are leverage Azure for that. 

Prerequisites

  1. Since Two-Factor Authentication using Azure Sphere is based on Azure Sphere device connected to user's machine, it is important to mention that the prerequisite of this system is to have Azure Sphere device properly connected the user's machine. Information on setting up Azure Sphere device with a machine is provide in previous blog post Getting started with Azure Sphere
  2. The second prerequisite is to make sure the Azure Sphere device has been added to an Azure IoT hub. More information for that can be found at Microsoft Docs article Set up an IoT Hub for Azure Sphere

Authentication Flow with Azure Sphere

As mentioned above the first step is validating the factor 1 which is typical user name and password authentication. The following steps illustrates the flow information and authentication mechanism for the factor 2 (security code):
  1. User provides the user name and password that is passed on to the authenticator (authentication provider). 
  2. The authenticator validates the user name and password thus completing the factor 1 authentication. 
  3. After that authenticator sends message to Azure Sphere device attached to the user's machine to generate a security code and instructs the user to press the Button 2 on the Azure Sphere device. Information on setting up Azure Sphere device is provide in prerequisite section mentioned above. 
  4. The Azure Sphere device receives the request through its connection to Azure IoT hub. 
  5. It then generates a security code, saves the security code in its mutable memory and posts the result to Azure IoT hub. 
  6. Azure IoT hub informs the authenticator (authentication provider) about the generated security code. 
  7. As instructed by the authenticator, the user presses the Button 2 on the Azure Sphere device. 
  8. The Azure Sphere device retrieves the saved security code and posts the information to Azure IoT hub. 
  9. The authenticator then receives the notification that user has pressed the Button 2 along with the security code that was retrieved by the Azure Sphere device from its mutable memory. 
  10. The authenticator then validates the security code retrieved previously when Azure Sphere generated the security code and when the Button 2 was pressed. 
  11. Based on the authentication result, the user is deemed authenticated or not.

Figure 2 - Two Factor Authentication using Azure Sphere


Conclusion

Although Azure Sphere is quite powerful and versatile, we have seen how we can leverage Azure Sphere and Azure IoT hub to provide the second factor authentication for a two-factor authentication system. There are other systems that can be build on top of the design that is presented here. If we look further, we can connect another device with Azure Sphere device that provide other uses. For example, we can provide a display to show the security code that is generated by the Azure Sphere device that can be entered into an interface provider by the authenticator.

In my next blog post, I have taken provided technical details on how Two-Factor authentication is implemented using Azure Sphere and Azure IoT hub. The details are provider at: Two-Factor authentication with Azure sphere and Azure IoT hub - Step by step

Comments are welcome.