
PowershellでADFSの証明書監視を行う
Windows関連はあんまりやる気ないんですけど、必要に迫られて作りました。
証明書の取得方法が分からなくて、悩んで3時間なんとか取れたのでここに貼っておきます。
カシマです。
スクリプト自体はもしかしたらもっと良いやり方はあるかもしれませんが、とりあえず動いたのでそのまま使えるはずです。
check-certificate.ps1の中身
$Certificate = Get-AdfsCertificate -CertificateType token-signing | Where { $_.IsPrimary } | Select-Object -property Certificate | Select -ExpandProperty "Certificate"
$CertificateGenerationThreshold = Get-AdfsProperties | Select-Object -property CertificateGenerationThreshold
$CertificatePromotionThreshold = Get-AdfsProperties | Select-Object -property CertificatePromotionThreshold
$Threashold = $CertificateGenerationThreshold.CertificateGenerationThreshold - $CertificatePromotionThreshold.CertificatePromotionThreshold
$ExpireDate = $Certificate.NotAfter.AddDays( - $Threashold )
$ToDay = (Get-Date)
$JudgeDate = ($ExpireDate).AddDays( - $ToDay.DayOfYear )
Write-Output("Certificate is expire in {0}.(There are {1} days left.)" -f $ExpireDate, $JudgeDate.DayofYear)
$code = 0
if( $JudgeDate.DayofYear -lt $Args[0] ){
$code = 1
}
if( $JudgeDate.DayofYear -lt $Args[1] ){
$code = 2
}
exit $code
最初に証明書情報から .NotAfter のプロパティを得るために証明書の情報を引っ張り出しています。
証明書情報の中身が確か通常のtype:propertyではなく、type:notepropertyとかいうものだったかな。
通常のプロパティならそんな悩まないんですけど、printしてみたらNotAfterが出てこないので
「取れてないのか??????」
と疑問に思ってました。
なんてことはなかったのですが、 .NotAfter
とやってプロパティアクセスすれば良かったようです。
それだけだったのか……とガッカリきましたが、あとはGet-AdfsPropertiesコマンドから証明書生成の間隔と切り替わるまでの間隔を得るのですが、諸々考慮した計算式となっています。
あとは今日の日付を取得し、その差分で判定するだけになります。
JudgeDataからpowershell引数で指定された日付の方がでかくなるようならexitコードを設定して返します。
あとはmackerel側なんだけどカスタムのチェックプラグインとして以下のようにmackerel.confに記述し、mackerel-agentをサービスから再起動すればOKです。
[plugin.checks.certificate]
command = ["powershell.exe", "-File", "C:\\check-certificate.ps1", "30", "7"]
notification_interval = 1440
max_check_attempts = 1
check_interval = 1440
timeout_seconds = 300
最初はincludeとして別のファイルに書いていたのですが、どうやら認識してくれなかったようで、うまく監視されずなんでだ?となってましたが、mackerel.confにひとまとめに書かなくちゃならんのですね。
LinuxとWindowsの違いでまさかこんなことがあるとは(笑)