AzSession: Connecting to Azure AD-joined VM’s
Microsoft has introduced a pretty cool feature where you can use Azure Active Directory credentials for AAA against a Linux virtual machine (see Microsoft Docs for more information). Getting signed in the first time is a bit cumbersome, but in my opinion worth it for the convenience and security.
There is, however, a massive caveat: you can no longer (trivially) SSH to the machine in an external client, as the AZAD sign-in flow generates an ephemeral key pair on the VM for you, and requires interop with AZAD to do so. The Azure CLI PowerShell module does offer a means to export a key, but due to its ephemeral nature, you can only use it for around an hour:
az ssh config --file '~./ssh/config' -n vmName -g resourceGroupName
This works fine with OpenSSH and anything that can either read its default configuration (~./ssh/config
or %USERPROFILE%\.ssh\config
) or take a configuration file as an argument.
However, exporting the config file to the default location won’t work if you already have a configuration file (presumably to prevent clobbering the user’s settings). Inconveniently, my best friend New-PSSession
doesn’t take a configuration file from the command line, so I had to find a work-around.
Now, when it creates a session over SSH, New-PSSession
uses OpenSSH under the hood, so it follows that it would respect the default user configuration. Thus, I created the AzSession PowerShell module to:
-
Get the VM’s public IP address
-
Temporarily rename the user’s SSH configuration.
-
Generate the ephemeral keys for the connection and associated configuration.
-
Copy the ephemeral configuration and keys to the default location.
-
Create a session with the VM.
-
Delete the ephemeral keys and configuration.
-
Restore the user’s configuration.