สวัสดีครับ ผม Chaba_OK! เราจะมาเรียนรู้การสร้าง PowerShell script file ให้มีความน่าเชื่อถือว่า ไม่โดนแก้ไขโดยใช้ Code signing certificate ซึ่งเหมาะกับการนำไปใช้งานใน Production System
เริ่มต้นต้องตรวจสอบก่อนว่า PowerShell ต้องเป็น version 4.0 ขึ้นไป
การ Sign ต้องใช้ Certificate ถ้าเป็นงาน Production เราควรใช้ Certificate ที่ออกจาก Certificate Authority แต่สำหรับการทดสอบเราจะใช้ Self-signed certificate สร้างด้วยคำสั่งนี้
จากคำสั่ง เป็นการสร้าง Certificate เพื่อทำ Digital Signature มีอายุ 5 ปี สำหรับ domain ชื่อ api.vm360degree.com ซึ่งหากตั้งเป็นชื่ออื่นที่เหมาะกับงานก็ได้ เมื่อสร้างสำเร็จ Certificate จะถูกเก็บไว้ที่ Local Machine วิธีเปิดดูให้กด [Windows]+[R] | mmc.exe | File | Add/Remove Snap-in … เลือก Certificates | Click ที่ปุ่ม Add > | เลือก Computer account | เลือก Local Computer | กด Finish ผลตามภาพด้านล่าง
ลำดับต่อไป เราจะต้องย้าย Certificate ไปเก็บไว้ที่ Trusted Root Certificate ด้วยคำสั่ง move-item การอ้างอิงถึง Certificate จะใช้ค่า Thumbprint ของ Cettificate ที่สร้างไปไว้แล้ว
จะได้ผลลัพธ์ตามภาพด้านล่าง
หรือ กลับไปเรียกด้วย PowerShell คือ
ตอนนี้เรามี Certificate – Code Signing พร้อมจะ Signed ซึ่งในตัวอย่าง ได้เตรียม file hello.ps1 มีหน้าตาแบบนี้
ใช้คำสั่งเพื่อสร้าง Sign ในภาพ
ในตัวอย่างผมใช้เครื่องหมาย ` เพื่อขึ้นบบรทัดใหม่โดยที่ยังไม่จบคำสั่ง ซึ่งในคีย์บอร์ดภาษาไทยเป็นตัวเปลี่ยนภาษา ก็ให้ copy ไปแปะแทนก็ได้ และหลังสัญลักษณ์นี้ห้ามเว้นวรรคให้ขึ้นบรรทัดใหม่ทันที ผลที่ได้คือในไฟล์ hello.ps1 จะมี Signature แปะไว้
วิธีการตรวจสอบว่าไฟล์ที่ Signed ไว้มีการแก้ไขหรือเปล่าให้คำสั่ง Get-AuthenticodeSignature ผลก็ได้ตามภาพด้านล่าง ปกติ Status ต้องเป็น valid แต่ถ้าถูกแก้จะได้เป็น HashMismatch
Script ที่ใช้ทั้งหมดอยู่ด้านล่าง
$MyCert = new-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\my ` | |
-DnsName api.vm360degee.com ` | |
-friendlyname api.vm360degree.com ` | |
-NotAfter ( [DateTime]::Now.AddYears(5)) ` | |
-KeyAlgorithm RSA ` | |
-KeyLength 2048 ` | |
-KeySpec Signature ` | |
-Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" ` | |
-KeyExportPolicy Exportable ` | |
-KeyUsage DigitalSignature ` | |
-Type CodeSigningCert | |
$MyPath = 'Cert:\LocalMachine\my\' + $MyCert.Thumbprint | |
Move-Item -Path $MyPath -Destination Cert:\LocalMachine\Root | |
$cert= Get-ChildItem cert:\localmachine\root -CodeSigningCert |?{$_.friendlyname -eq "api.vm360degree.com"} | |
Set-AuthenticodeSignature C:\work\Azure\cert\hello.ps1 ` | |
-Certificate $cert ` | |
-TimestampServer http://timestamp.comodoca.com/authenticode | |
Get-AuthenticodeSignature -FilePath C:\work\Azure\cert\hello.ps1 |
สรุป เราเรียนรู้ 2 เรื่องคือ
- การสร้าง Self-signed certificate ด้วย PowerShell ทำความเข้าใจให้ดี เพราะจะใช้งานต่อไปอีกในครั้งต่อไป เช่น Azure KeyVault, WinRM แบบ HTTPS
- การ Signed PowerShell Script เพื่อป้องกันการแก้ไข
สุดท้ายขอฝาก Facebook group – Azure Thailand User Group ไว้ด้วยครับ
Reference
Create Code Signing Certificate on Windows for signing PowerShell scripts
https://www.ddls.com.au/blog/creating-a-self-signed-certificate-for-powershell/