22

If I create an Azure Linux VM using PowerShell, how can I get its new SSH host key, so that I can install it in my local ssh/PuTTY? Preferably the solution is also PowerShell code.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Oliver Bock
  • 4,829
  • 5
  • 38
  • 62

7 Answers7

10

You can use a new "Run Command" feature of Azure Portal.

  • In your Virtual Machine page, go to "Run command" in "Operations" section of VM menu.
  • Select "RunShellScript" command.
  • Paste the following command:

    for f in /etc/ssh/ssh_host_*_key; do ssh-keygen -l -f "$f"; done
    
  • You will get an output like:

    Enable succeeded: 
    [stdout]
    256 SHA256:bKKCom8yh5gOuBNWaHHJ3rrnRXmCOAyPN/WximYEPAU /etc/ssh/ssh_host_ecdsa_key.pub (ECDSA)
    256 SHA256:IYeDl+gseYk46Acg4g2mcXGvCr7Z8FqOd+pCJz/KLHg /etc/ssh/ssh_host_ed25519_key.pub (ED25519)
    2048 SHA256:rA0lIXvHqFq7VHKQCqHwjsj28kw+tO0g/X4KnPpEjMk root@myazurevm (RSA)
    
    [stderr] 
    

    (the set of key types will vary with your VM image)


The feature can also be used via Azure CLI, what is shown in the link above and also in the answer by @mwik.


Check also my complete guide to Connecting securely to Microsoft Azure service with SFTP.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
9

Old question, but for newcomers there is nowadays an alternative available by using run-command in Azure CLI. There is probably an equivalent for PowerShell too, but I have not investigated that.

az vm run-command invoke --name <your-vm-name> --command-id RunShellScript --scripts "cat /etc/ssh/ssh_host_ecdsa_key.pub"

will output a json document from which you can extract the public key. Beware though that this process is incredibly slow (~30 seconds per host), but you only need to run it once. See this gist for an example of how to update the known_hosts file with Ansible.

mwik
  • 193
  • 1
  • 6
  • 4
    Nowadays you also need to add `-g` (or `--resource-group`), other than that, yes, that'd work, thank you very much! – wvxvw Oct 16 '18 at 07:05
  • The command can also be executed in Azure Portal, see [my answer](https://stackoverflow.com/q/32304208/850848#55846389). +1 – Martin Prikryl Apr 25 '19 at 10:14
2

The RSA, DSA, ECDSA, and ED25519 keys are generated on first boot, and available in the boot diagnostics log.

Key generation Key listing

If you don't catch it on the first boot, I don't think it's listed anywhere else in the portal. There's only one feasible, secure option of which I can think for recovering the fingerprint for an already-deployed VM.

  1. Create a new VM.

  2. Attach the VHD of the VM for which you need the fingerprint.

  3. Verify your connection to the new VM using the fingerprint in the boot diagnostics.

  4. Check the fingerprint for the generated /etc/ssh/ssh_host_rsa_key.pub file on the other disk.

    ssh-keygen -lf /{path}/ssh_host_rsa_key.pub

You may need to add the -E md5 switch if you need the hexadecimal encoded MD5 hash.

PowerShell

To get the boot diagnostics data via PowerShell:

Get-AzureRmVMBootDiagnosticsData -ResourceGroupName ExampleGroup -Name TestLab -Linux

Connecting with Putty

Azure computes the host key fingerprints as a Base64 encoded string of the SHA-256 hash of the public key. When you attempt to connect using Putty, it presents the fingerprint as a hexadecimal encoded string of the MD5 hash of the public key.

Fortunately, Azure also lists the full public key in the boot diagnostics log, where it says BEGIN SSH HOST KEY KEYS in the second image. With that, we can manually compute the fingerprint as presented by Putty.

C#

static string ComputeMD5FingerprintFromBase64(string encoded)
{
  // Convert Base64 string to byte array.
  byte[] pub = Convert.FromBase64String(encoded);

  // Compute MD5 hash.
  HashAlgorithm md5 = MD5.Create();
  byte[] hash = md5.ComputeHash(pub);

  return BitConverter.ToString(hash).Replace('-', ':');
}

Windows

For instructions on securely connecting to a Windows VM with RDP, see my answer on this StackOverflow question.

Community
  • 1
  • 1
lordcheeto
  • 1,092
  • 12
  • 16
  • 1
    This is a great answer. I haven't accepted it because Get-AzureRmVMBootDiagnosticsData cannot find my VMs, probably because they are "classic" VMs. Some day I'll put them under resource manager and give this a try. In the meantime please post a comment if this has worked for you. – Oliver Bock Oct 11 '16 at 05:24
  • To calculate the PuTTY/WinSCP MD5 fingerprint from the Base64-encoded key, just use this single-line command in PowerShell console: `Write-Host ([BitConverter]::ToString([Security.Cryptography.MD5]::Create().ComputeHash([Convert]::FromBase64String(""))) -replace "-", ":").ToLower()`. Source: https://winscp.net/eng/docs/guide_microsoft_azure#linux – Martin Prikryl Dec 21 '16 at 14:34
  • This answer unfortunately does not seem to help anymore. The boot diagnostic log does not contain the host keys anymore -- tested with the default *"Debian 9 Stretch"* and *"Red Hat Enterprise Linux 7.6"* images. – Martin Prikryl Apr 25 '19 at 09:52
0
ssh-keygen \   #Command to create ssh keys
-m PEM \  #Key format
-t rsa \ #Type of key
-b 4096 \ #Bits
-C "azureuser" \ #comment
-f terraform-azure.pem # SSH key name
Vivek Raj
  • 353
  • 3
  • 3
-1

Perhaps this is exactly what you're looking for. I will try it with you on my account right now.

Basically it looks like you need to attach a .pem upon creation. enter image description here

Which should yield your certificate thumbprint.
enter image description here

gh0st
  • 1,653
  • 3
  • 27
  • 59
  • Oops looks like @Ereli had come across the same article I had. – gh0st Sep 09 '15 at 23:00
  • It is interesting to see the SSH CERTIFICATE THUMBPRINT field here. It does not show up for the VM in the new portal.azure.com, but I can see it in the old manage.windowsazure.com. However it does not match the fingerprint I see when I first connect to the host via ssh, so I think that it is the key pair for the user account being created, not the host key. – Oliver Bock Sep 10 '15 at 00:13
  • he's looking for the hostkey, not the user auth key – joseph Nov 21 '16 at 20:41
-1

Windows VM Example

Select-AzureSubscription mysub $service = 'yourservicename1' $location = 'West US' New-AzureService -ServiceName $service -Location $location Add-AzureCertificate -CertToDeploy 'D:User-DatadevelopmentAzure Samplesmlwdevcert.cer' -ServiceName $service $cert1 = New-AzureCertificateSetting -Thumbprint D7BECD4D63EBAF86023BB4F1A5FBF5C2C924902A -StoreName 'My' New-AzureVMConfig -ImageName 'MSFT__Windows-Server-2012-Datacenter-201208.01-en.us-30GB.vhd' -InstanceSize 'Small' -Name 'win2012cert' | Add-AzureProvisioningConfig -Windows -Password 'somepass@1' -Certificates $cert1 | New-AzureVM -ServiceName $service

Linux VM Example

Select-AzureSubscription mysub $service = 'yourservicename1' $location = 'West US' New-AzureService -ServiceName $service -Location $location Add-AzureCertificate -CertToDeploy 'D:User-DatadevelopmentAzure Samplesmlwdevcert.cer' -ServiceName $service $sshkey = New-AzureSSHKey -PublicKey -Fingerprint D7BECD4D63EBAF86023BB4F1A5FBF5C2C924902A -Path '/home/admin/.ssh/authorized_keys' New-AzureVMConfig -ImageName 'CANONICAL__Canonical-Ubuntu-12-04-amd64-server-20120528.1.3-en-us-30GB.vhd' -InstanceSize 'Small' -Name 'linuxwithcert' | Add-AzureProvisioningConfig -Linux -LinuxUser 'mwasham' -Password 'somepass@1' -SSHPublicKeys $sshKey | New-AzureVM -ServiceName $service

Note: The -Certificates and -SSHPublicKeys parameters are arrays so they can accept multiple certificates. -SSHPublicKeys $sshKey1,$sshKey2

For Linux there is also the -SSHKeyPairs parameter for passing a key pair instead of just the public key. -Certificates can handle both types on Windows.

Nullpointer
  • 1,895
  • 20
  • 26
  • With the -SSHPublicKeys parameter, it is documented as "Specifies a list of SSH public keys already deployed in the subscription to deploy in the virtual machine.", which does not indicate whether it is the host key or keys for the new user account. The [REST documentation](https://msdn.microsoft.com/en-us/library/azure/jj157194.aspx) is also unclear, but gives /home/user/.ssh/authorized_keys as an example location for the keys, suggesting it is for user keys. When you run this and ssh to a VM for the first time, is the fingerprint that ssh asks you about is the same one you uploaded? – Oliver Bock Oct 07 '15 at 20:36
  • Oliver is looking for the host's key, not the user auth key – joseph Nov 21 '16 at 20:46
-2

In their help document, there is a page talking about how to reset the password or ssh key:

https://learn.microsoft.com/en-us/azure/virtual-machines/linux/troubleshoot-ssh-connection

spearous
  • 47
  • 1
  • 5
  • While this link may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this [how-to-answer](http://stackoverflow.com/help/how-to-answer) for providing quality answer. – thewaywewere Jun 11 '17 at 17:20
  • The question is about "host key", not about password or account key. – Martin Prikryl Jun 11 '17 at 18:33
  • Well, it is quite clear in the azure's manual in the link I put there, you just need to read it. – spearous Jun 13 '17 at 23:57
  • Well, I don't know how to post a picture, but in that link, what they said is clear to me. That is host key to a specific virtual machine. it is in the section "Use the Azure portal" under the "Available methods to troubleshoot SSH connection issues" part. – spearous Jun 14 '17 at 00:09