Showing posts with label Windows PowerShell. Show all posts
Showing posts with label Windows PowerShell. Show all posts

Tuesday, November 28, 2023

Azure @ Enterprise - Generate JWT using Service Principal +Certificate via MSAL.PS

One of the previous posts in this blog was to get JWT using the Service principal + certificate combination¹. The Az.Acount PowerShell module was used to achieve the task. That approach signs into Azure as the service principal and generates JWT. This post is to get the JWT without logging in.

MSAL.PS

Microsoft Authentication Library is to interact with the Microsoft security system recently renamed Microsoft Entra². 

There are also client-side libraries to interact with it from different languages. MSAL.PS is the library to do the same from PowerShell. Though the MSAL.PS³ is superseded by Azure Az PowerShell SDK⁴, it is still worth giving a try.

The below code shows how we can get the JWT using MSAL.PS.
The code is mostly straightforward but requires some basic understanding of the Azure security model, scope etc.

Making HTTP resource calls

Once we have the JWT, it can be used to invoke HTTP calls or to execute a SQL Query.
$token = Get-MsalToken @creds
 
$reqHeaders = @{
    'Authorization' = $token.CreateAuthorizationHeader()
}

$requestUrl = "<YOUR RESOURCE URL>"
Invoke-RestMethod -Uri $requestUrl -Headers $reqHeaders

The interesting thing is that the post published 2 years ago uses the up-to-date and officially supported method.
Happy working with legacy codebase.

References

¹ - https://joymonscode.blogspot.com/2021/09/azure-enterprise-powershell-log-in-as.html

² - https://learn.microsoft.com/en-us/entra/fundamentals/new-name | https://devblogs.microsoft.com/identity/aad-rebrand/

³ - https://github.com/AzureAD/MSAL.PS

⁴ - https://learn.microsoft.com/en-us/powershell/azure/new-azureps-module-az

Tuesday, August 22, 2023

PowerShell to write XML with attributes on new line

Context

Many times after patch deployment of the application into the server there will be questions on what changed? The source code is obviously changed and the binaries can't be compared to find out what changed.

But the textual configuration files can easily be compared. Take a backup of existing files. Do the patching and compare what changed.

This post is assuming the deployment tools are using PowerShell to change the config files.

Problem

Look at the image below.

It shows there are a lot of changes done to the file. But really there is only one change. dbserver3->dbserver2

As we can easily understand the comparison considered the files as text, not as XML, and found a lot of differences.

Approaches

If the number of files is less this is fine but that is not the case in enterprise. There are multiple approaches to this problem.

A tool that understands XML and compares

The above comparison tool is not recognizing the XML format instead it compared textually. Find another tool that understands the XML format and compare accordingly.

To date, we didn't find any such tool. Please comment if there are tools that are free and export the comparison report.

Always have attributes on a new line

In this approach make sure all the tools and programs that modify the XML write attributes on a new line.
Since PowerShell is running on top of .Net it is easy to get anything working in PowerShell that works in .Net. Google easily lands us in pages that say use the XMLWriterSettings.NewLineOnAttributes to get the job done. Unfortunately, it is not working out of the box.

But when we combine the .Indent property with .NewLineOnAttributes, it works fine.

[XML]$doc = get-content ".\input.xml"
$xwSettings = new-object System.Xml.XmlWriterSettings
$xwSettings.Indent = $true
$xwSettings.NewLineOnAttributes = $true
$xmlWriter = [Xml.XmlWriter]::Create("output.xml", $xwSettings)
$doc.Save($xmlWriter)
$xmlWriter.Dispose()

The above code works. Now the question is, is this documented? Oh yes in the remarks section.
Of course, the default value of the Indent property is false. The comparison looks as below after using the above code.


Happy formatting.

Tuesday, June 27, 2023

Azure @ Enterprise - Upload certificate to App registration using PowerShell

Warning

All characters and events in this post are fictional. Any resemblance or similarity to any actual events entities or persons is entirely coincidental

Developer: Hi there, as you know we are excited to release the next version that uses Azure AD-based authentication. All the 100 development, testing till prod deployment instances require their own Azure app registrations. Also, require certificates added for authentication to outside services. Certificates can be shared across lower environments.

Install Manager: Oh. It is not possible to have one app registration per application instance. It is not manageable.

Developer: What? Are you not paid for managing instances? Hope you are not doing charity.

Install Manager: Yeah I know you are funny. We cannot manage that many app registrations and certificates.

Developer: What do you mean by managing? 

Install Manager: Oh boy, higher environments are not like your toy dev instances. It is serious business. Do you know the certificates are not forever? On that day they expire, we need to upload a new certificate to all your dev and test app registrations.

Developer: Hey, we are in 2023. Don't you guys automate?

Install Manager: We don't do automation here.

Developer: It is not huge code. Just use the simple PowerShell commands that any system admin knows.

Install Manager: Enough boy. We don't have skilled people here. If you want, you code it and give it to us.

Developer: Oh ok..here you go.

Tuesday, April 18, 2023

Azure @ Enterprise - Azure app registration service principal to access selected SharePoint sites

Disclaimer - SharePoint Online as a "CMS to organize semi-structured content and documents via the user interface" is a promising technology. If you are integrating with an enterprise application, using its API and SDKs, or customizing, wishing you all the best.

Accessing the SharePoint Online Site Collection

Not so long ago below was the limitation with SharePoint

  • We cannot give permission for specific SharePoint site collections to an Azure app registration service principal.
  • If we use the service principal to access the site collections, it will get permission for all site collections in the tenant. In enterprise, other site collections may belong to totally separate divisions or applications.
  • If an enterprise wants to limit the applications to specific sites, they have to use any of the below methods
    • Service accounts - This means the application needs to keep the service account name and password. Use the ROPC flow³ which is not recommended by Microsoft itself. 
    • Separate tenant per application - Provision separate tenant per application, sync users, etc...
  • Service Account is viewed as a user from SharePoint Online and throttled more heavily than a service principal that is treated as an application. Have fun fighting production issues or retrying operations.

2021-02-11 - App access on a specific SharePoint Site Collection (Graph Only)

Microsoft announced a feature¹ that will allow applications via service principal permission to specific sites. As follows
  • In the Azure portal, we can give Sites.Selected permission to a service principal
  • Use the below API endpoint to give permission to the application ie service principal
    • https://graph.microsoft.com/v1.0/sites/{siteId}/permissions
    • This allows granting only Read, Write. Cannot manage sites with Full control
  • In order to give this permission the granting application or user identity needs to be in higher privilege.

Somehow Microsoft forgot the fact that the Graph API is not complete. There are many scenarios Graph API is not supporting and we have to fall back to CSOM/Legacy SharePoint APIs. Maybe some application teams might have leveraged this feature that was not even in GA status. But if it's a real SharePoint integration project they might not be. Anyway this is a good start

2022-08-11 - App access on a specific SharePoint Site Collection (GA and CSOM support)

Below are the updates² to the feature announced after one and half years.
  • Sites.Selected permission is applicable to CSOM API as well
  • The feature became generally available.
  • The site permissions API still allows granting only Read, Write. Cannot manage with Full control.
  • The official documentation is yet to be updated.
It looks like the below in the Azure portal after giving permission to both Graph and SharePoint (CSOM) APIs

Now below are the benefits to an enterprise with this change.
  • Permission sites to individual applications using the service principal. 
  • Applications, specifically daemon applications need not use a service account that has no throttling documentation and is heavily throttled.
  • Applications don't need to use ROPC flow where the password is involved and discouraged by Microsoft itself.

Sites.Selected with Full Control

One blogger figured out a hack to grant full access to service principals with Sites.Selected⁴ as follows.
  • Create write permission first. Full Control at the time of creation is not working.
  • Change that permission to Full Control.

Updates

2022-06-09 - Conditional access in GA

Some enterprises want to increase security posture by limiting the usage by allowing from limited IPs. Service Accounts as that capability earlier, the app registrations got that capability later. It first came in preview and as of 2023-06-09, it became production-ready ⁵.

References

Tuesday, January 25, 2022

PowerShell to list all the IIS Web Applications using IISAdministration

When it comes to automating Internet Information Services (IIS) Web server there are multiple choices. One with Appcmd command and the other with PowerShell. In PowerShell itself, there are different modules to manage. The WebAdministration is the legacy and IISAdministration is modern. More on that was written in a previous post about "Change recycle settings of IIS AppPools using PowerShell & appcmd.exe"

Let us get into the business of this post

Problem

There is an existing system that uses the on-premises model for hosting web applications. Windows Server 2019 + IIS is the hosting model. As the first step to the cloud, these servers were lifted and shifted to the Azure. Now to reduce the cost and time to market of course to improve the developer agility the IaaS model needs to be upgraded to containers. AKS is the preferred choice as it is in Azure. As part of the analysis and capacity planning the # of containers needs to be evaluated from the existing IIS-based deployment model.  ie count the web applications in IIS.

So this post is about listing all the web applications inside IIS web server that are spread across different IIS websites.

Solution

Since the last post about IIS automation was using WebAdministration, I thought of going with IISAdministration this time as it's the latest to replace the former.

Hope the code is self-explanatory. If the above embedding is not working please check the GitHub file.

Enjoy scripting...

Tuesday, September 21, 2021

Azure @ Enterprise - PowerShell to send message to Azure Service Bus Queue

We all know that Azure and PowerShell are friends. This post discusses how can we use PowerShell to work with the data place of Azure Service Bus. The example here is about queueing a message into the Service Bus queue.

Problem

We did implement a messaging architecture using Azure Service Bus Queue. The consumer is a .Net app that connects to the Service Bus Queue using Service Principal + Certificate. It works fine in lower environments such as dev, QA, etc... but stopped working in higher environments. Below was the message.

"An existing connection was forcibly closed by the remote host ErrorCode: ConnectionReset (ServiceCommunicationProblem);"

As it is a higher environment, there is no way we can install troubleshooting tools or even don't have access to the Azure portal.

Troubleshooting

Since there is no portal access and cannot install tools we decided to simulate how the application consumes Service Bus using PowerShell.

The first step was easy to connect to Azure using cmdlets using the Service Principal+Certificate and generate JWT. But the next step was not easy.

By the way, this requires the installation of Az.Accounts PowerShell module in the production machine. :)

Since PowerShell is considered an admin thing than a dev tool, admins normally allow it.

Challenge

The problem is that there is no official PowerShell package from Microsoft to work with the data place of ServiceBus. The official PowerShell module supports control plane functions such as create service bus namespace(New-ServiceBusNamespace), create queues (New-AzServiceBusQueue), etc. Even interacting with the data plane is not there in Azure CLI. We were not able to find any community-built PowerShell cmdlets too except for some tutorials on how to send messages.  

Solution

Finally, we had to get our hands dirty by making HTTP calls from PowerShell. The REST endpoints are properly documented to easily craft the requests. The PowerShell source code to send messages is available on GitHub.

https://github.com/ms-azure-demos/servicebus-queues-powershell

The root cause of the problem

When we run the PowerShell script from the same machine the app is running, it worked!!!. That eliminated the questions of what ports are open etc. The remaining difference between the .Net application sending messages v/s PowerShell was the AMQP v/s simple HTTP. .Net application uses AMQP by default and we didn't put an option in the application to fall back to HTTP. We checked whether the ports are open and they are. Hence concluded the higher environment network is not allowing AMQP traffic. Some network devices are on the way that doesn't like the AMQP traffic. 

Tuesday, September 14, 2021

Azure @ Enterprise - PowerShell log in as service principal + certificate and generate JWT access token

The enterprise always loves to increase the security posture. One authentication approach enterprise takes in Azure is App registration with a service principal. The advantage here is that the service principal can use certificates to authenticate instead of passwords. Certificates are secure than passwords as those can be centrally managed.

Problem

If our application uses the service principal + certificate and it is working fine, there is no issue. But the problem starts when something goes wrong. If we log in to the portal using our credentials and try scenarios that are failing, we may see everything works fine. But things go wrong when the application logs in using service principal. It may be a permission issue, expired certificates or passwords, etc...

What if the problems appeared first in production where enterprises don't allow any changes to the environment. ie no debugging tools are allowed to install etc...

Solution

The solution is to troubleshoot the scenario as close as how the application works. We have to log in as the service principal and try the application scenarios. 

As always in enterprise the best method to troubleshoot in production environments is PowerShell. Below goes the code to log into Azure from PowerShell using service principal and generating a JWT access token.

The Connect-AzAccount cmdlet provides different ways to log in. Using the service principal is one of the methods.
Please note that the Az.Accounts need a minimum of Windows PowerShell 5.1 or PowerShell 7 version.

Once the PowerShell session is authenticated, we can perform various operations as the service principal. 

In most cases, the access token is not really required. There are PowerShell SDKs for most of the Azure services. We can directly use them. But in some cases like interacting with the data plane of Service Bus, we may need to use the access token and embed it in the Authorization header of the HTTP request.

Limitations

It reads the certificate from the personal store unless loaded from a file. We cannot pass an X509Certificate object to the Connect-AzAccount cmdlet. There is already an issue in GitHub to track it.

Update : 2021-10-30

What if we don't have permission to install Az.Accounts module?

Recently, I came to one production debugging situation where there is no permission to install the Az.Accounts module and even no connectivity to the internet to get the module. The only way is to write everything ourselves. Fortunately, someone had already done that and it is available publicly. If interested read the official docs.

Tuesday, May 18, 2021

PowerShell to check if private key is there in certificate

This is a small tip that can be considered as a continuation of an older post.  That was about validating the X509 certificate using PowerShell. As we all know, PowerShell is the way to execute almost anything in production, where using any other software is prohibited. 

The new problem encountered was that the certificate is there but no private key. When we use that certificate to obtain the Azure AAD token it fails. Below goes the snippet to check. 

Tuesday, September 8, 2020

Setting up home NAS - Part 2 - PowerShell arrange media date bases files into YYYY\MM\DD folders

This is the third post in "Setting up home NAS". Other posts below

Setting up home NAS - Part 2 - PowerShell arrange media date bases files into YYYY\MM\DD folders (This post)

Background

This post is more about organizing and managing media files. Not about NAS specifically though this post is filed under the 'NAS' tag. As of writing this post, below is my setup and  I am happy
  • A router attached USB drive working as NAS. \\192.168.1.1\share. It is 1TB in size.
  • Sync the photos to my personal computer that has 500GB drive. SyncToy is working fine for on-demand sync
If you have a defined way and tools to organize the files, please skip this post.

Problem

One of the problems we are facing is the files from a variety of sources. We may have more than one camera, photos from social media such as WhatsApp, scanned old photos, etc...If we just label folders by event name or /oldphotos, /old1phots and /old2photos etc...it would be difficult in the future. So a better way is to arrange in folders based on the date taken
If we regularly move photos from all sources to our NAS device, it is easy we know what is the date and easily create and move to the right folders.
But, if we do it once in a month or two, it is difficult to put the files to the right folder.

Solution

There are GUI tools such as PhotoMove, Photos2Folders, or use IrfanView to move based on date. Even there is a command-line Exif tool to move the images bases on the modified date. But my media includes not only images, but it also has videos and audio files. Also, I may require a similar mechanism for other purposes in the future.

PowerShell to rescue

It may seem like overkill to write program to move files based on date. But I ended up coding PowerShell routine to do the same. Below goes the code. It's in gist

Tuesday, April 14, 2020

Change recycle settings of IIS AppPools using PowerShell & appcmd.exe

Background

The app pool recycle is a hack to hide our or .Net's poor memory management. When we refer poor .Net memory management, it means the LOH fragmentation which was not compacted in earlier versions of .Net CLR. Hence we need to set up the app pool recycle in IIS.

Changing or 'recycling' setting of an app pool in one server one time is easy and can be manual. But what if there are many app pools, servers and had to do multiple times. Obviously, it should be automated. This post is about some snippets about automating the same using some of the provided mechanisms.

AppCmd

This is a command which we can use to manipulate IIS programmatically from IIS 7 onwards. Location of appcmd.exe is [install drive]:\Windows\System32\inetsrv\appcmd.exe. Direct commands to manipulate IIS entities are very easy but chaining the commands is a little different. If we are from PowerShell background, we feel it very odd. It outputs XML and subsequent commands to read XML as input.

Below is a mix of PowerShell and AppCmd.exe to disable periodic recycling of app pools.

Import-Module WebAdministration
$pools= dir IIS:\AppPools
$pools | Foreach-Object{
    $appPoolName=$_.name
    $cmd="C:\Windows\System32\inetsrv\appcmd.exe set apppool /apppool.name: '$appPoolName' /-recycling.periodicRestart.schedule"
    Invoke-expression $cmd
}

As clear in the above snippet, the PowerShell iterates thought the AppPool and invoke the AppCmd.exe for each app pool with its name
Another drawback of AppCmd.exe is that we cannot manage remote machines using this command only. We need to combine with PowerShell to execute this command in the remote machine.

PowerShell

There are 2 PowerShell modules.

WebAdministration

  • This mainly gives a provider which we can query just like file system
  • Microsoft considers WebAdministration PowerShell module legacy and not bringing to Nano server. Clearly means someday WebAdministration will be discontinued from support.

IISAdministration


PowerShell Function to set Recycling

Though WebAdministration is considered legacy, this post uses that to achieve the job of managing AppPool recycling.

function Set-ApplicationPoolRecycleTimes {     
    param ([string]$ApplicationPoolName, [string[]]$RestartTimes)
    Import-Module WebAdministration       
    Clear-ItemProperty IIS:\AppPools\$ApplicationPoolName -Name Recycling.periodicRestart.schedule       
    foreach( $restartTime in $RestartTimes)
    {
        New-ItemProperty -Path "IIS:\AppPools\$ApplicationPoolName" -Name Recycling.periodicRestart.schedule -Value @{value=$restartTime}           
    }
}

It has 2 parameters. First it clears the existing settings and then applies the new settings.Below is the method to call function to clear recycling. Just skip the second parameter $RestartTimes to clear the property.

Set-ApplicationPoolRecycleTimes -ApplicationPoolName 'DefaultAppPool'

The code below shows how to call the function to set new times. The parameters can be given just comma-separated or as and string array.

Set-ApplicationPoolRecycleTimes -ApplicationPoolName "DefaultAppPool" -RestartTimes "1:00","2:00","14:00"

Please note that the times expected are in 24-hr clock format. If we use the AM or PM what the IIS manager shows, this script will error with cast exception.

Let's see how we can manage all the app pools in a machine.

Applying to all the pools

Just loop all the app pools and call the function.

$pools= dir IIS:\AppPools
#$pools | ForEach-Object { Set-ApplicationPoolRecycleTimes($_.name) }

PowerShell has Invoke-Command to run scripts in remote machines. The same method can be used to control IIS in remote machines.

References

https://www.habaneroconsulting.com/stories/insights/2013/set-the-specific-times-to-recycle-an-application-pool-with-powershell
https://forums.iis.net/t/1229302.aspx

Tuesday, November 12, 2019

Power BI Desktop Dashboard for IIS Log Analysis - Improved performance of PowerShell data prep script

This is the third post in the "Power BI Desktop Dashboard for IIS Log Analysis" series.

Power BI Desktop Dashboard for IIS Log Analysis
Power BI Desktop Dashboard for IIS Log Analysis - C# for IIS log parsing instead of PowerShell
Power BI Desktop Dashboard for IIS Log Analysis - Improved performance of PowerShell data prep script

Here we will be discussing how the data preparation process is enhanced by just using the LogParser command. In the initial versions, the time to prepare CSV from the .log file was high if the cs-byes and sc-bytes columns were missing. That is because the approach taken was to load the CSV file into PowerShell and add additional columns with a default value.

This time the approach changed a little bit and completely avoided the need to load CSV files into PowerShell. Logic is as follows

  1. Try to convert the input log files as-is on the assumption that the log contains all the required fields including cs-bytes and sc-bytes. This uses LogParser.exe
  2. In case of error, use the same LogParser.exe file with a slightly different query which selects '0 as cs-bytes, 0 as sc-bytes'. 
Click here to see the code changes in GitHub repo.

The fix is not rocket science. It is an obvious thing everybody knows but unfortunately missed in the earlier phase. Thanks, Wade Mascia for pointing out.


Happy Analyzing...

Tuesday, October 15, 2019

[Video] - Power BI Desktop Dashboard for IIS Log Analysis - Step by step instructions to prepare IIS Logs files and loading into PBI

Today lets see how to prepare IIS Log files to load into Power BI Dashboard. The 'software-performance' GitHub repo contains sample IIS Log files along with the tools. We can use the same for the demo.

Prerequisites

Below are the prerequisites to complete the steps which help us to analyze IIS Logs via Power BI.

  1. A machine with Windows OS as all the tools used are compatible with Windows only.
  2. Basic understanding of Windows PowerShell
  3. LogParser utility
  4. Of course the Power BI Desktop application.

Steps

Let's see the steps

  1. The first, step is to clone the 'software-performance' GitHub repo into a local directory. How to clone a repo is not in the scope of this tutorial. Please refer to the link provided. Let's consider is it cloned into c:\source\repos folder
  2. Second step is to convert .log files into .csv. Open Windows PowerShell ISE better "run as administrator". Then navigate to the cloned folder where the IIS to CSV.ps1 file is available.
  3. Once we open the IIS to CSV.ps1 file, make sure the variable $pathToLogParserExe has the correct path to the installed logparser.exe file
  4. Change the value of $inputPath to the folder where IIS Log files are located. Let's use the sample logs provided in the software-performance repository.
  5. Run the script by clicking the button of press F5
  6. It will convert the .log files to .csv files. We can see the CSV files created in the same folder of input log files.
  7. Now open the Power BI sample file present in the repo
  8. Click on the Edit Queries drop-down then- > Data source settings
  9. We can see the current folder used. Click on the 'Change Source' button in the bottom left. Enter the path to the folder where CSV files created
  10. Press Ok then Close buttons.
  11. Finally, click on the 'Refresh' button. It will load the data from files into Power BI and render reports.
It may take more time depending on the size of CSV files. Normally the speed is observed as 1MB/second.

The same steps along with a short description of dashboards available in the below video

Tuesday, September 10, 2019

PowerShell to run same SQL to multiple databases in multi tenant system

Background

Multi-tenant systems are complex by nature and not everybody works on multi-tenant systems even in the Enterprise. In those systems, the boundary has to be clearly defined between tenants. It is mainly due to the noisy neighbour/tenant. No one wants to get disturbed by others in the same system. Some systems use all the tiers separated from the web server itself. Some separate only the database by sharing web and processing tiers. There is no one rule how to separate the tenants.

If we are maintaining a multi-tenant system with every tenant has their own database with identical structure, it is a question most of the time how to apply structural / schema changes quickly. Below is one method which is easy to apply a hotfix to all.

PowerShell script

This script iterate through all the databases in the SQL Instance then executes the SQL in a file specified. That file may contain an alter table, SP changes, etc...

# NOTE* It is advised to test on dev server before higher environments
# ----------------------------------------------

$Inst = "<Your sql instance with port number if applicable>"

$filepath = "<file path to sqlfile>"


# $databases grabs list of databases. Adjust the where condition to filter.

$databases = invoke-sqlcmd -ServerInstance $Inst -Database "master" -Query "select name from sys.databases where database_id > 4 and name <> 'TEST'"


foreach ($database in $databases)
{
    $DBname = $database.name
    # Outputs one file per database
    $outfile = $filepath + "."+$database.name+".log"
    #Execute scripts
    Invoke-Sqlcmd -ServerInstance ${Inst} -Database $database.name -InputFIle $filepath | out-file -filepath $outfile

    $database.name
}

Note 

This assumes there is only one SQL instance in the system and takes care of the databases inside. But in the real situation, huge multi-tenant systems will have multiple SQL instances.

Tuesday, March 5, 2019

Azure @ Enterprise - Write-Host v/s Write-Output in Kudu console

Recently we were troubleshooting in one Azure WebAppBot application. It needs certificates to access some secrets from Azure KeyVault. After some debugging, we reached to a place where we suspect that the certificates added are not getting accessed by the WebApp. So we decided to test the availability of certificates using Kudu PowerShell console.

Get-childitem Cert:\CurrentUser\My -recurse | %{ write-host $_.Subject }

Unfortunately we got some other issue.

PS D:\home> Get-childitem Cert:\CurrentUser\My -recurse | %{ write-host $_.Subject ; }
Get-childitem Cert:\CurrentUser\My -recurse | %{ write-host $_.Subject ; }
write-host : The Win32 internal error "The handle is invalid" 0x6 occurred
PS D:\home>
while setting character attributes for the console output buffer. Contact Microsoft Customer Support Services. At line:1 char:50 + ... hilditem Cert:\CurrentUser\My -recurse | %{ write-host $_.Subject ; } + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [Write-Host], HostExcep tion + FullyQualifiedErrorId : SetConsoleTextAttribute,Microsoft.PowerShell.Com mands.WriteHostCommand

It seems the PowerShell capabilities what we have in VMs is not the same what we have in WebApp's Kudu console. Even a simple Write-Host "Hi" also failed.

So tried to use Write-Output instead of Write-Host which writes to stream than to the host.

It worked!!!

Happy debugging.

Tuesday, February 26, 2019

PowerShell to check whether the .Net assembly is compiled into debug or release

Often as part of reviews we need to check whether the application deployed is compiled in release mode or not. Most of the CI/CD tools compile in release mode only. But if some has modified any assemblies post deployment manually and missed to compile in release mode, it is worth checking the assemblies.

It is easy to run PowerShell in productio environments than running a tool to check. Running an external exe is often makes discomfort to the production support guys. Essentially running a PowerShell script and custom tool are same from technical perspective. But since the PowerShell source is plain text and production support guys are familiar with PowerShell, they normally allow.

This is not my creation. Got from somewhere in the internet and posting here so I can use it next time.

Get-ChildItem -Filter *.dll -Recurse |

    ForEach-Object {

        try {
         $Assembly = [Reflection.Assembly]::LoadFile($_.FullName);
         $type = [System.Type]::GetType("System.Diagnostics.DebuggableAttribute");
         $debugAttribute = $Assembly.GetCustomAttributes($type,$false);
         If ($debugAttribute.count -Eq 0) {
            "{$_.Name} :Release"
         }
         ElseIf ($debugAttribute[0].IsJITOptimizerDisabled -eq $false) {
            "{$_.Name} :Release"
         }
         Else {
            "{$_.Name}  :Debug"
            }
        } catch{ "{$_.FullName} ***ERROR*** Error when loading assembly: " }                 

    }

Make sure the PowerShell is in the right folder context so that it can get the files using *.dll filter.

A .Net version is available in Hanselman's blog.

Tuesday, January 15, 2019

PowerShell to validate certificate

Scenario

There is a WPF based enterprise application working based on certificate issued into the system by the certificate authority. When the application starts it make sure there is a certificate in the store which is issued by the enterprise. For remote service calls, certificate chain based trust is used to ensure the WCF communication is secured. The servers will accept the client request which comes with certificate issued by the same certificate authority of what is in server.

Problem

One day accidentally someone issued one more cert to the client machine in the same name. Then the poor application stopped working as it doesn't know what to do when there are more than one certificate.

Panic situation started. Some are sure that in such situation one of the certificate should be revoked. Some tells application should have intelligence to choose the cert with longest expiry, etc... 

How to understand what is really happened? Need to look into one of the client machine to which developers barely have access. So don't even think about installing or giving an test application. 

Modifying the application is not a big deal but without understanding what is happening is waste of time. The problem here is understanding what is happening in client machine. This might seem very silly to a fresher or someone working for public products. Welcome to Enterprise, it doesn't work that way in Enterprise.

PowerShell to rescue

The PowerShell is really a revolution where it helps developers to run code in restricted environments otherwise they cannot do anything via installer or utility exe. .bat files were there, but that won't let developers run C# code as is in a machine without compilation.

Lets see the snippet which will help us to check whether the certificates are revoked or not.

Get-childitem Cert:\CurrentUser\My -recurse | %{ write-host $_.Subject ; Test-Certificate -cert $_ }
The main API is the Test-Certificate command let. The initial code fragments are used to iterate the certificate store.

Happy scripting...

Tuesday, November 6, 2018

PowerShell to find the listening port and its process - eg SQL Server Analysis Service

Problem

Enterprise environment always enforce security in different levels. One such level is network ports. There will be less questions when we want to open port 443 for http(s) communication. Also it is fine if the ports are familiar such as 1433 for SQL Server. But when it comes to some unfamiliar ports its difficult. Also they wants to open very minimal ports. So finding and documenting exactly what ports are required is a considerable job for an Architect. This is obviously not applicable to Architects who are there when solutions or define the solution themselves. But its trouble for Architects who reverse engineer what is in the development / testing / staging environment and prepare document which is essential to move the application to the higher environment.

One such thing is SQL Server Analysis Service. For SQL Server OLTP engine its easy to find out. But for analysis service, its difficult if the installation is done using custom port.

What Google says

This is not the first time people encounter the problem and there are lot of solutions to it. Some from google are below.

To find ports and processes in general

http://blogs.microsoft.co.il/scriptfanatic/2011/02/10/how-to-find-running-processes-and-their-port-number/
https://stackoverflow.com/questions/42857466/find-process-that-is-blocking-a-port-on-windows

https://superuser.com/questions/1215093/powershell-one-liner-to-show-process-on-same-line-as-port-using-netstat-issue

Find SSAS Ports

https://support.microsoft.com/en-us/help/2466860/how-to-determine-and-change-the-port-of-an-ssas-instance
https://www.cisco.com/c/en/us/support/docs/conferencing/telepresence-management-suite-analytics-extension/112506-pqa-112506-00.html#q1

The general scripts are either based on long custom PS command or text analytics based. The SSAS port findings required 2 steps to figure port out.

Easy solution using PowerShell

Below is another one which does the things in singe PS command. Yes obviously there is piping and we can argue whether its multi-line script or not.

Finding ports and processes


Get-NetTCPConnection | `
where {$_.State -eq 'Listen'} | `
select -Property LocalAddress, `
                        @{name="Process";Expression={$psid = $_.OwningProcess; (Get-Process | where {$_.Id -eq $psid }).Name + ', ' + $_.OwningProcess}}, `
                        LocalPort ` |
sort -property Process

Pretty much straight forward. It relies on the Get-NetTCPConnection commandlet. Then does some filtering and selection to get the list back.

Finding port of SSAS Service

We can apply the above technique easily to filter the SSAS process

get-nettcpconnection | `
where {$_.State -eq 'Listen'} | `
where {$_.OwningProcess -in (Get-Process | Where {$_.Name -eq 'msmdsrv'}).Id} | `
Select-Object -Property LocalAddress, `
                        @{name="Process";Expression={$psid = $_.OwningProcess; (Get-Process | where {$_.Id -eq $psid }).Name + ', ' + $_.OwningProcess}}, `
                        LocalPort `


It takes a big assumption that the process name of SSAS is 'msmdsrv'. In future Microsoft change the name the script will not work.

References

Tuesday, September 4, 2018

PowerShell to get list of email addresses from company AD

Often we may need to send mail to everyone to the company as an announcement or requesting urgent help etc...Normally companies might have a group mail address to do such things. Even if there is none we can easily get the list of all emails

First to get the OU and DC details of your AD. If there are confusion on what is OU, DC refer the details here. Better search using your email id itself to get the OU and DC details.

Get-ADUSER -Filter 'EmailAddress -like "<your email address>"'

This will give the details in the DistinguishedName property. Now fill that information in below script and run.

$container = "OU=<your OU>,DC=<DC>,DC=<DC>"

get-ADUSER -Filter * -SearchBase $container | `
select -Property UserPrincipalName | `
Export-Csv -Path "<path>.csv"

This export the email addresses to the csv file mentioned. It is interesting to see that the UserPrincipalName has the email. If the email is kept separately, the code has to be modified to select proper attribute.

Happy Scripting...

Tuesday, August 21, 2018

PowerShell to create databases from backup

Below is PS code snippet to restore many databases from one DB backup. Useful if we need to load test. There could be version mismatch issues if we directly use the RelocateFile class. So use the small hack as shown in the snippet.

1..100 | foreach { 

    $sqlServerSnapinVersion = (Get-Command Restore-SqlDatabase).ImplementingType.Assembly.GetName().Version.ToString() 

    $assemblySqlServerSmoExtendedFullName = "Microsoft.SqlServer.SmoExtended, Version=$sqlServerSnapinVersion, Culture=neutral, PublicKeyToken=89845dcd8080cc91" 

    $RelocateData = New-Object "Microsoft.SqlServer.Management.Smo.RelocateFile, $assemblySqlServerSmoExtendedFullName"('<Data file group name in backup>', "<data folder>\$_.mdf") 
    $RelocateLogs = New-Object "Microsoft.SqlServer.Management.Smo.RelocateFile, $assemblySqlServerSmoExtendedFullName"('<Log file group name inbackup>', "<Log folder>\$_.ldf") 
    $RelocateFG = New-Object "Microsoft.SqlServer.Management.Smo.RelocateFile, $assemblySqlServerSmoExtendedFullName"('<any more file group name eg File stream>',"<data folder>\$_") 

    Restore-SqlDatabase ` 
        -ServerInstance "<server name>\<instance>" ` 
        -Database "<db name>$_" ` 
        -BackupFile "<path to bak file>" ` 
        -RelocateFile @($RelocateData,$RelocateLogs,$RelocateFG) 

    "Restored $_ DB" 
}

Some points

  • Change the value from 100 to increase the number of databases needed. 
  • The new DBS will be created with the number suffixed to their names. 
  • Relocating file is required. Else there could be collision with previous database.

Tuesday, July 31, 2018

Azure @ Enterprise - Time bound SAS for WebJob to dequeue ServiceBus Queue messages

Context

Enterprise in 'Azure @ Enterprise' series refers to companies or projects which have stringent security measures and process guidelines which a normal developer may not think of. Or are not expected in the self service cloud world. Often the security measures are taken to make sure that the responsibility is moved to some other party or vendor so that people at Enterprise are free from low level details of those concerns.

If we are in non enterprise projects, developing a queued back end processing in Azure is super cool with Azure Queue and WebJobs. But in enterprise that is not the case, we have to make sure the service supports virtual network or not. Will that support encryption at rest as well as in transit. If it encrypt can the enterprise provide key etc...Basically enterprise don't want to fully trust the cloud vendor though in reality vendor own all and have full control.

Problem

Enterprise may evaluate Azure ServiceBus Queue is better than the Azure Storage Queue as per current feature sets and the standards what it used to evaluate. It may come out viceversa. If it demand key rotation for ServiceBus connection string with expiry, it is little difficult, if we had used only configuration(web.config or app.config) based connection string.

Even if it is not enterprise project, it is good practice to rotate the keys with expiry as long as the ServiceBus don't support hosting it inside the vNet. If it support hosting inside vNet, the attack surface could be less. Currently any Tom,Dick or Harry can launch brute force attack against the service bus end points.

Key rotation will not remove the attack surface but reduce the possibility of a successful attack.

https://feedback.azure.com/forums/216926-service-bus/suggestions/15619302-add-service-bus-to-vnet

Solution

It is possible to have key rotation even with the attribute based WebJob functions. We can have expiry to the keys as well. Lets see step by step.

Generating time based SAS (Shared Access Signature)

It is supported in ServiceBus. In order to generate one we need one Shared Access Policy. Normally when we create the SB instance, there will be 'RootManagerSharedAccessKey' with primary and secondary keys.

Ideally this is supposed to be done outside of the main application such as Azure Automation Code and the generated new time based SAS has to be in KeyVault. This will help to have only automation account knowing the high privileged Shared Access Policy key and WebJobs know only KeyVault secret name where the the time based Shared Access Signature is stored by Automation Runboook. If application has access to the KV, it can retrieve the SAS. 

Since the code to do SAS rotation using Azure Automation Runbook is not under the scope of this post, omitting that code. If anyone request through comments section, the code will be provided.

WebJob to read SAS and dequeue

Now lets come to WebJob code side. Before we start the JobHost to listen using RunAndBlock() on the thread, there is option to override to specify the connection string to the ServiceBus which uses the time based SAS. Below goes the code.

private static void RunAndBlock()
{
    var config = new JobHostConfiguration();
    config.UseServiceBus(ServiceBusConfigurationFactory.Get());

    if (config.IsDevelopment)
    {
        config.UseDevelopmentSettings();
    }
    var host = new JobHost(config);            
    host.RunAndBlock();
}

static class ServiceBusConfigurationFactory
{

    /// <summary>
    /// Returns the SB configuration
    /// </summary>
    /// <returns></returns>
    /// <remarks>Change this to read from Azure KV</remarks>
    internal static ServiceBusConfiguration Get()
    {
        return new ServiceBusConfiguration() {
            ConnectionString = BuildsSBConnectionString(GetITimeSensitiveSASTokenProvider().Get()),
        };
    }

    private static string BuildsSBConnectionString(string sharedAccessSignatureToken)
    {
        ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder();
        builder.SharedAccessSignature = sharedAccessSignatureToken;
        builder.Endpoints.Add(new Uri("https://<name of SB instance>.servicebus.windows.net/"));
        string finalCon = builder.ToString();
        return finalCon;
    }

    private static ITimeSensitiveSASTokenProvider GetITimeSensitiveSASTokenProvider()
    {
        return new KVBasedimeSensitiveSASTokenProvider();
    }
}

The code is mostly self explanatory. When the first time main() of WebJob is started, it will get the ServiceBusConfiguration from the factory class. Factory uses provider class which knows how to talk to Azure KV or some other store where the SAS is present. Once the SAS is present, the connection string can be built from it.

One thing to remember is that the SAS is not connection string. Connecton string has to be 

Things to remember when working with ServiceBus

API Collision

There are 2 dependencies when we work with Azure ServiceBus. Microsoft.Azure.ServiceBus.dll & Microsoft.ServiceBus.dll and they both has classes with same name. Sometimes its very difficult to get the code compiled if downloaded as snippet.

What if the token expires after RunAndBlock() is invoked?

At least in testing there were no issues to the dequeued messages. All new instances of WebJob process, it takes the new connection string.