0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerShell で sudo モドキを作ってみた[2. 接続設定]

0
Last updated at Posted at 2026-01-21

注意

 自己責任でお願いします。これら記事の内容を実行して何か不都合を被ったとしても筆者は責任を負いません。
 性質上セキュリティホールを自分で開けているようなものなので、実装は実験目的かつ仮想環境を推奨します。また当たり前ですが実装自体には管理者権限が必要です。また自分の所有する端末のみで行ってください。
 もし sudo を使いたいなら、Windows 標準 か Grignoli 氏の gsudo を使えばよいと思います。

構成

目次
1. 変数の宣言と代入
2. 接続設定
3. 構成ファイル作成・登録
4. 権限設定
5. 証明書作成
6. 証明書紐付け
7. 実行・関数作成
8. 後始末

説明

 PowerShell 用の WinRM を有効にします。これをもって遠隔から PowerShell セッションを確立することができるようになりました。しかし今回は自分自身からしか接続しないため、開放されているポートを閉じたり、待ち受け IP を localhost に限定したりしています。
 ちなみに再構成すると削除したものは復活します。

内容

使用する変数:
$RegLmPath $WsManPath $WinRmPath

$RegLmPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN"
$WsManPath = "WSMan:\localhost"
$WinRmPath = "winrm/config"

↓すべて管理者権限で実行します↓

WinRM 有効化・127.0.0.1 のみでリッスン・外部ファイアウォールは遮断
# WinRM 有効
Enable-PSRemoting -Force -SkipNetworkProfileCheck
# 既定で登録されている Microsoft.PowerShell セッション構成での接続を拒否
Disable-PSSessionConfiguration -Name *

# 確認
Get-ChildItem $RegLmPath\Listener
# 既存の構成を削除
Get-ChildItem WSMan:\localhost\Listener | Remove-Item -Recurse -Force

# 自接続(localhost から)のみを許可(ローカル専用 HTTP リスナー作成)
New-Item $WsManPath\Listener -Force -Address "IP:127.0.0.1" -Transport HTTP

# 接続先(localhost: 自分自身)を信頼
Set-Item $WsManPath\Client\TrustedHosts -Value "127.0.0.1,localhost" -Force

# リモート接続の場合は UAC を経由せずに昇格させる(既定: 自動で設定される)
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" LocalAccountTokenFilterPolicy 1 -Type DWord

# WinRM 用ファイアウォール: 80/5985 を遮断(ローカルループバック通信は標準許可・必要であれば追加で明示的に 5986 を遮断)
Get-NetFirewallRule -Name "WINRM-*" | Set-NetFirewallRule -Enabled False

# 確認
Get-WSManInstance $WinRmPath/listener -Enumerate
Get-ChildItem $WsManPath\Client
Get-NetFirewallRule -Name "WINRM-*"
再構成したい場合
# 一旦初期化
Disable-PSRemoting -Force
Stop-Service WinRM -Force
Set-Service WinRM -StartupType Disabled
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" LocalAccountTokenFilterPolicy 0 -Type DWord

# 再度構成
Enable-PSRemoting -Force -SkipNetworkProfileCheck
Enable-PSSessionConfiguration
Enable-PSSessionConfiguration -Name *
Set-Item $WsManPath\Client\TrustedHosts -Value "127.0.0.1,localhost" -Force

# 確認
winrm get $WinRmPath
winrm enumerate $WinRmPath/listener
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?