Last active
August 4, 2021 10:08
-
-
Save mahalel/cf0bce2bb39b75d57328976782aaf2f5 to your computer and use it in GitHub Desktop.
Powershell script to export all Root CA certs from the Windows Cert store and into WSL certificate store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
This script will export certificates based on your input from the Windows Certificate store and add it to your WSL Distro certificate store. | |
Requirements: | |
1. You have an idea of the certificate issuer and name. | |
2. You have WSL installed. | |
#> | |
# Read the cert name | |
$company = Read-Host 'Enter your certificate name' | |
try { | |
# Get path in WSL env | |
$wsl_path = wsl pwd | |
} | |
catch { | |
Write-Host "WSL not found - Please install WSL and try again." -ForegroundColor Red | |
} | |
# Get a list of all Certificates in Local Machine store where either the Issuer and Subject contain your input. | |
$all_certs = @(Get-ChildItem -path Cert:\LocalMachine\* -Recurse | Where-Object { $_.Issuer -like "*$($company)*" -and $_.Subject -like "*$($company)*" } | Select-Object -Property * ) | |
if ($all_certs.Length -eq 0) { | |
Write-Host "No certificates found for your input, try again." -ForegroundColor Yellow | |
} | |
else { | |
# Iterate through the certificates | |
$all_certs | ForEach-Object { | |
try { | |
$cert = Get-Item $_.PSPath | |
# Construct a sane filename | |
$file_name = "$($_.Subject -Replace 'CN=' , '' -Replace ',.*' , '' -Replace ' ' , '_').pem" | |
# Construct a path in Windows env | |
$file_path = "C:\Users\$env:UserName\$file_name" | |
# Export the certificate content in Base64 | |
$cert_content = @( | |
'-----BEGIN CERTIFICATE-----' | |
[System.Convert]::ToBase64String($cert.RawData, 'InsertLineBreaks') | |
'-----END CERTIFICATE-----' | |
) | |
# Write content to file in Windows env | |
$cert_content | Out-File -FilePath $file_path -Encoding ascii | |
# Move files from Windows path to WSL certificate store | |
wsl -u root -e mv $wsl_path/$file_name /etc/ssl/certs/ | |
Write-Host "Imported " -ForegroundColor Green -NoNewLine; Write-Host $file_name -ForegroundColor Red -NoNewLine; Write-Host " to WSL Certificate store" -ForegroundColor Green | |
} | |
catch { | |
Write-Host "Could not process certificate with thumbprint: $($_.Thumbprint)" -ForegroundColor Red | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment