2026年1月24日土曜日

RDP で毎回認証を求められるがそれを回避して認証情報なしで自動で接続する方法

RDP で毎回認証を求められるがそれを回避して認証情報なしで自動で接続する方法

概要

ダウンロードした RDP ファイルをコピーして書き換えて実行します 前回の続きです

環境

  • Windows11

monitory_rdp_file.ps1

param(
    [Parameter(Mandatory=$false)]
    [string]$RDPServer = "your.rdp.server.or.ip",
    
    [Parameter(Mandatory=$false)]
    [string]$RDPUsername = "domain\username",
    
    [Parameter(Mandatory=$false)]
    [string]$RDPPassword = "xxxx",
    
    [Parameter(Mandatory=$false)]
    [switch]$TestMode = $false
)

# Basic file logging to help diagnose scheduled task behavior
$logDir = Join-Path $env:LOCALAPPDATA "RDPFileMonitor"
if (-not (Test-Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}
$logPath = Join-Path $logDir "monitor.log"

# Emit a simple startup marker
("Started: " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) | Out-File -FilePath (Join-Path $logDir 'started.txt') -Append -Encoding utf8

try {
    Start-Transcript -Path $logPath -Append -ErrorAction SilentlyContinue | Out-Null
} catch {}

# Get user profile path - handle both system and user context execution
$userProfile = [Environment]::GetFolderPath("UserProfile")
if (-not (Test-Path $userProfile)) {
    $userProfile = "C:\Users\username"
}
$downloadFolder = Join-Path $userProfile "Downloads"
$targetRDPFileName = "rdgateway101_vdgate_nifcloud_net.rdp"
$processedFiles = @()

Write-Host "Starting RDP file monitoring (polling method)"
Write-Host "Executed by: $env:USERNAME from host: $env:COMPUTERNAME"
Write-Host "User Profile: $userProfile"
Write-Host "Log: $logPath"
Write-Host "Target folder: $downloadFolder"
Write-Host "Target file name: $targetRDPFileName"

if ($TestMode) {
    Write-Host "Test Mode: Running one iteration only"
} else {
    Write-Host "Checking every 2 seconds..."
}

$iterationCount = 0
$maxIterations = if ($TestMode) { 1 } else { [int]::MaxValue }

while ($iterationCount -lt $maxIterations) {
    $iterationCount++
    Write-Host "Iteration $iterationCount at $(Get-Date -Format 'HH:mm:ss')" -ForegroundColor Gray
    
    try {
        if (Test-Path $downloadFolder) {
            # Clean up processed files list - remove entries for files that no longer exist
            $processedFiles = @($processedFiles | Where-Object { Test-Path $_ })
            
            $files = Get-ChildItem -Path $downloadFolder -Filter "*.rdp" -File
            
            foreach ($file in $files) {
                if ($file.Name -eq $targetRDPFileName -and $file.FullName -notin $processedFiles) {
                    Write-Host "Target file detected: $($file.Name) at $(Get-Date -Format 'HH:mm:ss')"
                    Write-Host "Full path: $($file.FullName)"
                    
                    Start-Sleep -Seconds 2
                    
                    try {
                        Write-Host "Executing RDP file: $($file.FullName)"
                        
                        # If credentials provided, cache them and modify RDP file
                        if ($RDPUsername -and $RDPPassword) {
                            Write-Host "Caching credentials for: $RDPServer"
                            
                            # Cache credentials using cmdkey (more reliable than embedding in RDP)
                            $cmdkeyCmd = "cmdkey.exe /generic:$RDPServer /user:$RDPUsername /pass:$RDPPassword"
                            Invoke-Expression $cmdkeyCmd | Out-Null
                            Write-Host "Credentials cached successfully"
                            
                            # Read original RDP file
                            $rdpContent = Get-Content -Path $file.FullName -Encoding ASCII
                            
                            # Remove or disable credential prompting settings
                            $rdpContent = $rdpContent -replace 'prompt for credentials:i:1', 'prompt for credentials:i:0'
                            $rdpContent = $rdpContent -replace 'promptcredentialonce:i:1', 'promptcredentialonce:i:0'
                            $rdpContent = $rdpContent -replace 'enablecredsspsupport:i:1', 'enablecredsspsupport:i:0'
                            
                            # Ensure username is set in RDP file
                            if ($rdpContent -notmatch 'username:s:') {
                                $rdpContent += "`r`nusername:s:$RDPUsername"
                            } else {
                                $rdpContent = $rdpContent -replace 'username:s:.*', "username:s:$RDPUsername"
                            }
                            
                            # Create temporary RDP file
                            $tempRDPPath = [System.IO.Path]::GetTempFileName() -replace '\.tmp$', '.rdp'
                            Set-Content -Path $tempRDPPath -Value $rdpContent -Encoding ASCII
                            Write-Host "Temporary RDP file created: $tempRDPPath"
                            
                            Start-Sleep -Seconds 1
                            
                            # Execute temporary RDP file with cached credentials
                            Start-Process -FilePath $tempRDPPath
                            $processedFiles += $file.FullName
                            Write-Host "Executed successfully with cached credentials"
                            
                            # Clean up temporary file after a delay
                            Start-Sleep -Seconds 3
                            Remove-Item -Path $tempRDPPath -Force -ErrorAction SilentlyContinue
                            Write-Host "Temporary RDP file cleaned up"
                        }
                        else {
                            # Execute without credentials modification
                            Write-Host "No credentials provided, executing original RDP file"
                            Start-Process -FilePath $file.FullName
                            $processedFiles += $file.FullName
                            Write-Host "Executed successfully"
                        }
                        
                        Start-Sleep -Seconds 1
                        Remove-Item -Path $file.FullName -Force
                        Write-Host "File deleted: $($file.FullName)"
                    }
                    catch {
                        Write-Error "Error executing RDP file: $($_.Exception.Message)"
                    }
                }
            }
        }
        else {
            Write-Host "Download folder not found: $downloadFolder"
        }
    }
    catch {
        Write-Error "Error during monitoring: $($_.Exception.Message)"
    }
    
    # For test mode, exit after one iteration
    if ($TestMode) {
        Write-Host "Test mode iteration complete. Exiting."
        break
    }
    
    # Normal mode: sleep before next iteration
    Start-Sleep -Seconds 2
}

Write-Host "RDP file monitor stopped at $(Get-Date -Format 'HH:mm:ss')"
Stop-Transcript -ErrorAction SilentlyContinue

最後に

RDP ファイルは中身はテキストなのでいろいろハックできます

0 件のコメント:

コメントを投稿