Search code examples
linuxazurepowershellx509certificatex509

Authenticate to Azure with certificate from Linux


I am trying to log in to Azure from a Powershell Core script with Az module. This requires using a self signed certificate that is uploaded to Azure.

I tried creating a certificate using:

openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout /etc/ssl/private/key.pem -out /etc/ssl/private/cert.pem -subj "/C=LV/ST=Some-State/L=LV/O=IT/OU=IT"

and using the thumbprint to login, but Powershell gives me this error:

Connect-AzAccount : Unix LocalMachine X509Store is limited to the Root and CertificateAuthority stores.

Not sure what this means.

Problem is similar to this issue https://github.com/Azure/azure-powershell/issues/8658

But not sure how to interpret the answers there. No experience with certificates and limited exp with Linux.


Solution

  • To answer my own question, I finally somewhat figured it out. Steps:

    #create certs
    openssl req -new -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.cer -days 365 -subj /CN=localhost
    
    #create pfx
    openssl pkcs12 -export -out localhost.pfx -inkey localhost.key -in localhost.cer
    
    #You will need to specify some password for it
    #Now use the generated cer file and import it in your Azure portal, AzureAD->app registrations->your created SP->Certificates and secrets. Can also use powershell to do this.
    
    #import the PFX to your machines cert store
    $StoreName = [System.Security.Cryptography.X509Certificates.StoreName]::My 
    $StoreLocation = [System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser 
    $Store = [System.Security.Cryptography.X509Certificates.X509Store]::new($StoreName, $StoreLocation) 
    $Flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable 
    $Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new("path to your pfx","the pfx password you specified on step 2",$Flag) 
    $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) 
    $Store.Add($Certificate) 
    $Store.Close() 
    
    $tenantId = 'look in your azure portal' 
    $appId = 'app id of the service principal you created, look in your azure portal'
    $thumbprint = $certificate.thumbprint
    
    Connect-AzAccount -ApplicationId $appId -Tenant $tenantId -CertificateThumbprint $thumbprint
    

    That's it, you will automatically, non-interactively connect to your Azure tenant from a Linux machine or Docker, using Powershell Core and can execute all the commands your SP role allows. You can re-use the PFX file, just first time is manual, afterwards host it somewhere and load it with a script using curl or similar.

    Note: I don't know much about certificates and what security implications all this could have, use at your own risk.