Showing posts with label Azure AD. Show all posts
Showing posts with label Azure AD. Show all posts

Sunday, April 25, 2021

How to Restrict Azure Firewall Access from Contributor, Owner Role?

 7 min to read.

Abstract

When I look at Azure Built In Role Documentation I always feel this is really big list of built in roles and hardly any Organization will require to create new Azure custom role.

However when you work with Azure Customers, your faith and beliefs are bound to fail. And if your customer is Bank, your concepts of Security will fail.

So my customer started big on Azure Firewall. It was maintained by their network administrators team. One fine day network admin discovered that the Azure Firewall is visible to all users with Contributor and Owner access.

Obviously the demand came that Owner/ Contributor should have full access EXCEPT Azure Firewall.

Damn Zero Trust!

Anyways, How to hide/ restrict Azure Firewall access from Azure Owner and Contributors? Read on…



Have you heard of Azure custom roles?

The solution is simple. We need Custom Owner and Contributor role that will have default access levels except for Azure Firewall.

Azure Built in Roles list is here - https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles.

If the Azure Built In Roles don’t meet the specific needs of your organization, you can create your own custom roles.

So we will need to build custom Owner and Contributor role that do not have access to Azure Firewall.

Always get Built in Role Definition first!

For simplicity I am going to build custom Contributor Role only. Same can be replicated for Owner Role too.

First let us grab the built in role definition of Contributor Role using Azure PowerShell.

If you do not have Azure PowerShell get it installed or use it from Azure Shell. I want to edit the role definition on my local laptop so I am using Azure PowerShell from my local machine.

First login to correct Azure Subscription and Azure AD. I have seen major bomb blasts due to wrong selection of Subscription and Azure AD Tenant.

Connect-AzAccount -Subscription YourSubscriptionID  -Tenant YourAzureADTenantName-Like-Something.onmicrosoft.com

Get Contributor Role definition in JSON format with below command –

Get-AzRoleDefinition -Name "Contributor" | ConvertTo-Json | Out-File "YourPath\Contributor.Json"

 

Make sure that correct Path is selected as per your choice in above command. The Contributor role definition JSON will be created at specified location and it looks similar to below screenshot. Open JSON in Visual Studio Code. [click to get better view].



Modify the Contributor Role to Restrict Azure Firewall access!

I copy pasted above Contributor Role JSON to another document in VS Code changed the name of file..

The name of the role I changed to “Contoso-Contributor.json”.

Now take quick steps as mentioned below –

1.      Remove the Id filed completely. When you create role in Azure PowerShell; ID filed automatically gets created for you.

2.      As this is going to be customer Azure Role; change “IsCustom” property to True.

3.      Change the description that suits to your needs. I changed it to – Contoso Contributor Grants full access to manage all resources, but does not allow you to assign roles in Azure RBAC, manage assignments in Azure Blueprints, or share image galleries. However  users with this role can't access Azure Firewall.

4.      To remove the firewall access we need to add below line in NotActions segment of JSON as below – Microsoft.Network/azurefirewalls/*"

When we added * above, this means all types of actions are removed / restricted for Azure Firewall Resources. Make sure that you add “comma” on second last line.

5.      Make sure you add the desired subscription at the bottom in “AssignableScopes” property. Unless subscription Id added the role will not be created. The format of subscription has to be as follows -

Refer to screenshot below – [click to get better view].



Create the Role Definition in Azure Subscription

Now run below PowerShell command to get the role created. Make sure you use the Path of your choice where Contoso contributor json definition is present.

New-AzRoleDefinition -InputFile "YourPath\Contoso-Contributor-NoFirewallAccess.json"

 

The output of the command will be shown as below – [click to get better view]



Assign the role to user

I have created a user named as Contoso User in My Azure AD as shown below – [Click to get better view]



Then go to Azure Subscription -> Subscription -> Select Subscription [which is used in AssignableScope] -> Access Control -> Add -> Role Assignment. Selected Contoso User and assigned custom contributor role – [click to get better view]



Verify Azure Firewall Access

So, I selected two users – One with Contributor role and other with Contoso-Contributor Role. When click on Azure Firewall; I can clearly see that even If the Contoso User has all the access same as normal Contributor; the Azure Firewall Resource is not visible – [click to get better view].



Conclusion

Hope this article helped to Custom Contributor role to restrict / hide Azure Firewall.

Happy access control!!

A humble request!

Internet is creating a lot of digital garbage. If you feel this a quality blog and someone will definitely get benefited, don't hesitate to hit share button present below. Your one share will save many precious hours of a developer. Thank you.

Next Related Posts

4VNETs and transitive Routing using Azure firewall

Azure Virtual Machines – real world frequently asked questions – not easily answered.

Azure Migration frequently asked questions, not easily answered!

Azure VM disk encryption, what should be my approach!

Bypass onpremises firewall to RDP or SSH into Azure VM

Friday, April 17, 2020

Azure Function for generating Azure AD Token using .NET core

10 min to read.


Abstract

Development is a struggle, a continuous struggle. With serverless this struggle is becoming more and more imminent. Developers are still trying to get comfortable to serverless technologies.

Azure Function is one of the key serverless offering today on Azure. Azure Function is becoming backbone for many serverless and micro service based applications.

Recently after writing Azure AD token generator using .NET Core; immediately got a lot of requests to make this code run in Azure Function and here we are!

So in this blog we will create Azure Function to generate Azure AD token using .NET core.

Let’s go!

Architecture

Refer to below diagram [Click to get better view] for overall components used for running this code in Azure Function.



To publish the code of Azure AD token generator using .NET core to Azure Function, I plan to use Visual Studio. Publish operation from Visual studio to Azure Function is deployed as .zip file.

When we create Azure Function, creating an Azure storage account is also important and mandatory step. When we publish code from Visual studio, behind the scene Azure Files share is created in associated storage account and .Zip is actually copied to File Share.

This File Share will then mapped to Azure Function compute behind the scene and then used for running the actual application from Bin folder as shown above.

To get administrative access to runtime of Function keys are used. These keys are stored securely in Blob Storage which also get automatically created in the associated Storage account.

Making Azure Function async

First create Azure function project as shown below in Visual Studio – [click to get better view]



If you have seen the GitHub code of Azure AD Token generator using .NET core, you will observe that entire code is built using Async mechanism and token is also received in async way. When we create Azure Function project by default Azure Function startup method is not async. So let us make it async as shown below – [Click to get better view]



Then copy the code from GitHub and remove all Console specific methods. Instead make all methods to log information as shown in below screenshot – [click to get better view]



Publishing from Visual Studio

After completing code changes, it is time to publish to Azure Function. Either you can create new Azure Function from the Azure portal and specify the same during Publish method or simply create new Resource Group, Function from Visual Studio publish screen itself. In this tutorial, I am creating new Azure Function from Azure Portal as shown below – [click to get better view]



I have created TimerTrigger function. Then click on Publish button of your Azure Function project from Solution Explorer and make sure you select existing Function to create Publish Profile as shown below – [click to get better view]



Then continue further to publish to Azure Function.

Benefits of running Azure function from package file

Now in above screenshot of Creating profile you might have observed as checkbox – “Run from a package file”.
This is really important. This directly sets the Azure Function to run from package file only. Means your Azure Functions runs directly from a deployment package file in your Function App. By running function from package file you –

       1.      Reduces the risk of file copy locking issues
2.      Improves performance of Function App drastically
3.      Code start time is reduced
4.      Unwanted files are automatically removed from final deployment package.

My current Function app is based on Windows and .NET core therefore in Architecture diagram you might have observed below setting –

WEBSITE_RUN_FROM_PACKAGE = 1

This setting tells Function app to run from package file. You can also view this setting from “Application Settings” tab in Azure Function as shown below – [click to get better view]



Other ways of deployment

I can also write the code Azure function directly in Azure portal editor. However I have seen lot of issues in adding Nuget package reference in Azure function. Deploying from Visual Studio[for .NET code], VS code [all other languages including .NET] makes it easy in all respect; as all dependent assemblies, files get packaged in .zip.

When you deploy the Azure Function from Visual Studio with .zip package deployment; automatically your Azure Function will become read only and will show message as shown below –

Your app is currently in read only mode because you are running from a package file. To make any changes update the content in your zip file and WEBSITE_RUN_FROM_PACKAGE app setting.

Well, this is fine because anyways deployment is governed by Visual Studio. So we don’t need to make any changes in the code from portal. So Function becoming read only is fine. Rest of the platform specific features never become read only.  So I will definitely recommend to deploy the Azure function using VS or VS Code or using DevOps.

Verifying the .zip package and Azure File Share

After deployment, you can verify that .zip package is actually present in Azure File Share of the storage account and it is mapped to D drive on Kudu Console of Azure Function. See below - [Click to get better view]



Running the Azure Function and view the Azure AD Token

Run the Function and you should be able to view the generated Azure AD Token as shown below – [Click to get better view] –



I created TimerTrigger Azure Function to get Azure AD token on timely basis. This is because my next blog is based on Azure API Management monitoring which requires Azure AD token generation on timely basis from Function. You can also use HttpTrigger for Azure Function to generate Azure AD Token. So stay tuned for next blog soon!

Conclusion

Hope this article helped you to get Serverless Azure Function for generating Azure AD token using .NET core. Let me know your views in comments section below to improve and what are your thoughts on this approach.

Happy token generating!!

A humble request!

Internet is creating a lot of digital garbage. If you feel this a quality blog and someone will definitely get benefited, don't hesitate to hit share button present below. Your one share will save many precious hours of a developer. Thank you.

Next Related Posts








Saturday, April 4, 2020

Azure AD Token Generator using .NET Core

10 min to read.

Abstract

Change is inevitable. With .NET Framework becoming legacy and .NET core stated as future; many migration projects are getting triggered. Also for new projects, development choice is .NET core by default.

Last year in April 2019 I wrote a blog post on How to create service principal or App registration in Azure AD.

This is one of the most visited blog post. Reason is simple. Any functionality having requirement of invoking Azure REST API requires Azure AD token generation. This helps in performing management tasks against Azure environment; and hence it is crucial.

The last year blog is based on .NET framework.

With .NET core becoming more and more obvious choice, I thought it is time to have new blog post and new code base for “.NET core based Azure AD Token generator using Service principal.”

Let’s go!


Why I need to generate the Azure AD Token?

This is common question I get. What are the scenarios where I need to generate Azure Ad token from code and use it? Therefore below diagram lists few tasks where I will use Azure AD token generator code. Click on below diagram to get better view.



App registration and assign permissions to Azure AD application

The concepts of Azure AD Service principal, application registration, process of creating service principal remains same for .Net core too.

The only change we will see is in codebase.

So follow my earlier blog and perform below tasks –
       1.       Create Azure Service Principal by app registration
2.      Record Tenant ID, Application ID and Secret key
3.      Assign correct permissions to Azure AD app

By following earlier blog if you are still not clear then refer to document to understand – How and Why applications are added to Azure AD.

.NET Core code base for Azure AD token generation


Let us understand the code base for .NET core. The code now fundamentally is different than .NET framework. However Tenant ID, Application ID and Secret Key of Azure AD will be leveraged same as .NET framework code.
Build confidential client application as below – [click to enlarge]



This class is present in Nuget package Microsoft.Identity.Client and I am using 4.10.0 version for this project.


Azure AD authentication has many flows applicable. The current flow we are using in our code is “Azure AD Client Credentials” flow. For client credential flow we have to provide scope.

Scope is a boundary for which granted access token will be valid. If you request token for one scope and use for another; request will be denied. Example, you provide scope while requesting token from Azure AD as https://api.loganalytics.io/ [Log analytics resource scopes].

Means with generated token we can perform operation ONLY on Log Analytics. Post getting token if you try to access Azure Storage resource with scope as https://storage.azure.com/ then it will be denied. So providing correct scope is crucial.

The format of scope for “Client Credentials” is always of the shape “resource/.default”. So configure the scope as below. In my example I am leveraging scope for Azure Log Analytics. [click to enlarge below].



Now for this scope we retrieve the Access Token as below – [click to enlarge].



Further we can use this token with Postman to perform Azure management operation. Alternatively, we can also integrate this code in Azure functions, or applications to get token at runtime without user credentials and perform required administrative operation against azure environment.

Download  code

Entire code is available for download from github at the link  - https://github.com/kunalchandratre1/AzureADTokenGeneratorNETCore

Conclusion

Hope this article helped you to get quick code for generating Azure AD token using .NET core. Let me know your views in comments section below to improve and what are your thoughts on this approach.
Happy token generating!!

A humble request!

Internet is creating a lot of digital garbage. If you feel this a quality blog and someone will definitely get benefited, don't hesitate to hit share button present below. Your one share will save many precious hours of a developer. Thank you.



Next Related Posts

Start stop multiple Azure VMs and save cost. This uses Azure AD application behind the scenes.

Wednesday, October 30, 2019

Assign and verify Microsoft Azure AD custom domain using Azure App Service Domains

10 minutes to read.

Abstract


Have you ever heard of the word Doppelganger? It means ghostly double or counterpart of living person. There is theory that says, In today’s world there are 7 people who look similar to you. There are 6.4 billions basepairs in Human DNA. So I don’t trust this theory. However humans made sure that when it comes to internet world, there is one thing always unique – domain names. Domain names are very critical and there have been many famous domain name battles on uniqueness. One of the famous domain name battle was “Microsoft vs. MikeRoweSoft”. What? You never heard of it? Go search the internet.

Domain names can make or break an identify for your business. Custom domain names are inevitable in today’s world. If you want to be successful with your business/ website then custom domain name is a must. Microsoft Azure services also need custom domain names so that instance of Microsoft Azure services names can be aligned with your business / company names.

Azure AD is central to any Microsoft Azure based environment. All subscriptions belong to Azure AD and Azure subscriptions related identity management is also managed through Azure AD. Any Azure AD created will always have form as “YourAADInstanceName.onmicrosoft.com”. So when you create a user in Azure AD the FQDN of Azure AD user will be “username@YourADInstanceName.onmicrosoft.com.” Example I have an Azure Active Directory named “SanganakAuthority.onmicrosoft.com” then user “kunal” will have FQDN as “kunal@SanganakAuthority.onmicrosoft.com”. This is definitely not a user friendly name. If I change it to kunal@SanganakAuthority.com then it appeals a lot.

So custom domain for Azure AD is good to have thing!

Best thing is you DON’T have to go for external domain registrars/ providers like GoDaddy, HostGator, Bluehost etc. Microsoft Azure provides domain names through Azure App Service domains and you can use it anywhere including Azure AD.

Let’s go!

Relationship in Domains Names, DNS Records, DNS Zones and equivalent Microsoft Azure services

This is important to know aspects such as Domain Names, DNS Zones and DNS Records concepts in general and in Microsoft Azure platform. Refer below important diagram.



Domain names are provided by domain name registrars. Owning the domain names gives you right to control the DNS hierarchy. These purchased domain names are hosted on DNS names servers in terms of DNS Records. The domain registrar has their own name servers or they also allow you to specify your own/ preferred name servers. You host the domain names on name servers as DNS Records like A records, CName record, Txt record and so on. The combination of Names servers and DNS records is called as DNS Zones.
For purchasing domain names Azure provides “Azure App Service domain” and for DNS Zones Azure provides service called as “Azure DNS”.

Sunday, August 11, 2019

Azure API Management Disaster Recovery in Standard – Part 2 – Traffic Manager with custom domain and way forward

Abstract

In the first part - https://sanganakauthority.blogspot.com/2019/08/azure-api-management-disaster-recovery.html we have configured below things –

1.      Created required resources in primary and secondary region
2.      Configured the Azure AD application and provided necessary permissions
3.      Configured the backup and restore functionality for Azure API Management and automated the same using Azure Logic Apps. This is crux of our DR solution of API Management in Standard sku.

In this part we will configure below things –

1.      Traffic manager configuration for distributing load to primary always and to secondary in case disaster.
2.      Configure the status page of API Management in traffic manager
3.      Configure custom domain and certificate for API Management and traffic manager
4.      Test the failover by downgrading one of backend APIs and mocking the response
5.      Benefits of approach and conclusion

Traffic Manager configuration

Create traffic manager as per the link described in secondary region resource grouphttps://docs.microsoft.com/en-us/azure/traffic-manager/quickstart-create-traffic-manager-profile#create-a-traffic-manager-profile .

Provide values as shown below –



Note the URL of API Management standard instances from primary and secondary instances as shown below  and highlighted by green line –




We will use these URLs as an “External endpoint” in traffic manager profile. Configure the traffic manager endpoint as shown below. Secondary API Management as priority 2 and primary API Management as priority 1.





Configure Health Status Page of API Management in Traffic Manager

Azure API Management Disaster Recovery in Standard – Part 1 – Backup and restore configuration

Abstract

This blog post explains step by step configuration for achieving Azure API Management DR in Standard sku. This bog post is divided in 2 parts series. Links to all parts is as below –



Being intelligent human being you can directly go to any of the part; but I would recommend to go ahead sequentially from Part 1 to Part 2 of the blog post. This will ensure that there are no mistakes. Ask any questions in comments. If I see that question asked is already answered in any of the part of this series; please don’t expect the answer to the question asked.

Till now we have seen two important blog post aboutAzure API Management custom Role Based Access Control and Need of API Gateway in modern architectures as concept.

This blog post takes another deep dive discussion in API Management DR configuration.

Azure API Management Disaster Recovery in Standard – the need?

Azure API Management as of today offered in various pricing sku with various features –1.    Consumption
2.      Developer
3.      Basic
4.      Standard
5.      Premium.


When you onboard API Management as a part of your API story for all of your Enterprise applications; this component becomes mission critical. As a best practice we should also configure Disaster Recovery (DR – multi region deployment) for API Management.
API Management DR is by default provided as a service in Premium sku. However at the same time the capacity or workload support by premium sku is massive. Therefore premium sku also comes with premium price. Sometimes enterprise needs are observed to get satisfied by BASIC or STANDARD pricing tier. As of today as a bench marking of API Management with STANDARD tier support approx. 2500 req/ seconds per unit. STANDARD tier can have up to 4 units. Means total number of requests that can be served by STANDARD API Management can go up to 10000 req/ sec. This is massive scale and may satisfy most of the Enterprise requirements. However STANDARD sku do not provide Disaster Recovery [DR] pre-configured. This may propose bigger challenge for organizations who are betting big on Azure API Management.

This document provides step by step document for configuration of DR for API Management STANDARD sku along with architecture. Hope this document will help to address the concern of API Management DR in Standard/ Basic mode.

List of Azure service used in the API Management DR with Standard

As a part of the solution we will use below services in Azure to implement API Management DR in standard mode.
  1. 2 Logic apps – for automation of backup from primary region and restore in secondary region of API Management
  2. API Management in two regions – Central India(Primary - CI) and South India(Secondary - SI)
  3. Traffic Manager – to distribute the load in case of DR situation
  4. Storage account – for storing backup information of API Management primary
  5. Azure AD application – to allow logic app provide authentication mechanism to make changes in API Management (through ServicePrincipal concept).


High Level Steps

The gist of this article is based on backup and restore feature of “API Management” management REST APIs. The REST API documentation is present below –



These APIs allow backup and restore operation for entire Azure API Management instance and it is crux of our solution. Refer to high level steps for the solution below.

  1. Create two API Management in Standard mode. One in primary [in our case Central India] and other in secondary [in our case South India].
  2.  Configure APIs and related backend in API Management primary. As you API Management standard is not part of VNET, the backend APIs will require public IP to get imported in API Management.
  3. Create Azure AD Application to have necessary permission to make changes in API Management instances in cross region.
  4. Allow rights on resource groups of both API Management in two regions.
  5. Create two logic apps. One to create backup of primary API Management. Second will be used to restore the same backup in secondary region API Management.
  6. Create traffic manager and add API Management IP address/ domains names as endpoint profiles. Configure Traffic manager in Failover/ Priority mode.
  7. Configure status page of API Management in Traffic manager to know health status of API Management for traffic manager so that it can switch to secondary region in case of DR situation.


Architecture for API Management DR in Standard Sku




  1. Logic app uses timer orchestration step to automatically trigger itself. As a next step same logic app sends service principal details to Azure AD and then retrieves the authentication token.
  2. Invoke API Management rest API with operation as backup.
  3. The operation starts copying data to storage account in other region. Depending on the size and number of APIs being used in Azure API Management the backup operation takes approximately 1-2 hours [this may change based on the data present in your API Management instance. Don’t quote me if it takes more/less time than I mentioned].
  4. Post successful copy operation of backup; another logic app is triggered which restores the backup data in another API Management instance created in secondary region.
  5. Post restore operation both API Management instances are now exactly identical. For example, in secondary API Management all policies, subscription key, APIs etc. will be same as primary API Management.
  6. The request from end user/ application is received to traffic manager. Traffic manager is configured in failover mode with primary API Management as active and secondary API Management as passive.
  7. Traffic manager passes on the incoming request to active API Management instance.
  8. The health status page of both API Management instances /status023456789abcdef keeps sending 200 response to traffic manager. In case if primary status page sends non-200 response then Traffic manager will route the traffic to secondary API Management automatically.

Step by step execution