I wanted to connect over Remote Desktop (RDP) from my PC to a Windows Server on AWS EC2, without opening RDP port 3389 to the internet. So I used port forwarding in AWS Systems Manager (SSM) Session Manager.
The method itself isn’t new, but “authenticate, type a long command, launch Remote Desktop…” every time is quietly tedious. So I made a batch file that gets you all the way to an RDP connection with one double-click. For authentication it uses aws login, newly added to the AWS CLI. I like that no access key has to be stored on the PC.
Short answer: run aws ssm start-session with AWS-StartPortForwardingSession to forward local port 13389 to the instance’s 3389, then mstsc /v:localhost:13389. The batch file below wraps the login check, the tunnel, the wait, the RDP launch.
I previously wrote about connecting to a home PC with Tailscale, no port forwarding; this is something like the AWS version.
- Why this method
- Environment, architecture
- Prerequisites
- Required IAM policies
- Authenticate with aws login
- First, connect by hand
- A batch file that connects in one click
- Gotcha 1: closing RDP says “An error occurred while saving to Default.rdp”
- Gotcha 2: launching with an .rdp file warns “Unknown remote connection” every time
- Connecting to several instances
- Bonus: a version that leaves no credentials on the PC
- Summary
Why this method
- No need to open 3389 in the security group. No inbound rule on the EC2 side
- No bastion host or VPN to set up
- With
aws login, no access key to issue, store on the PC - As a batch file, connecting is just a double-click
Environment, architecture
- Local PC: Windows 11
- AWS CLI 2.33.22
- Session Manager plugin 1.2.779.0
- Target: Windows Server on EC2 (Tokyo region)
The local Remote Desktop just connects to port 13389 on your own PC; beyond that, the SSM tunnel carries it to port 3389 on EC2.
Local PC
Remote Desktop (mstsc) → localhost:13389
↓
Session Manager plugin (aws ssm start-session)
↓ encrypted tunnel over HTTPS (443)
AWS Systems Manager
↓
SSM Agent on EC2 (Windows Server) → port 3389 (RDP)
EC2 only makes outbound connections to SSM, so no inbound traffic to EC2 needs to be allowed. That’s why no port has to be opened.
Prerequisites
EC2 side
- SSM Agent running (already included in AWS-provided Windows Server AMIs)
- An IAM role with permissions for Systems Manager attached to the instance (next section)
- EC2 able to reach the SSM endpoints (internet access, or VPC endpoints)
If the instance shows up in Fleet Manager in the Systems Manager console, the EC2 side is ready.
Local PC side
- AWS CLI v2 (
aws loginneeds version 2.32.0 or later) - Session Manager plugin (installed separately from the AWS CLI)
Check whether they’re installed:
aws --version session-manager-plugin --version
Required IAM policies
Permissions are needed in two places: the IAM role attached to EC2, the person connecting (IAM user). In both cases, attach AWS managed policies for a quick setup, or write custom policies to narrow things down.
| Attach to | Quick: AWS managed policy | Narrow: custom policy |
|---|---|---|
| EC2 IAM role | AmazonSSMManagedInstanceCore |
ssm:UpdateInstanceInformationssmmessages:CreateControlChannelssmmessages:CreateDataChannelssmmessages:OpenControlChannelssmmessages:OpenDataChannel |
| IAM user (aws login) | SignInLocalDevelopmentAccess |
signin:AuthorizeOAuth2Accesssignin:CreateOAuth2Token |
| IAM user (Session Manager) | AmazonSSMFullAccess (too broad; not recommended) |
ssm:StartSession (on the target instance plus the AWS-StartPortForwardingSession document)ssm:TerminateSessionssm:ResumeSessionssmmessages:OpenDataChannel (on your own sessions) |
The custom policies below are built from AWS documentation samples, adapted for this use. Required permissions can vary by environment, so test with a trial user first.
IAM role for EC2
As an AWS managed policy, attach AmazonSSMManagedInstanceCore. It bundles the permissions for Systems Manager’s core features in general, not just Session Manager, e.g. Run Command. If you use Systems Manager for other things too, this is fine.
If you only need Session Manager, a custom policy can narrow it to these five actions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:UpdateInstanceInformation",
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
],
"Resource": "*"
}
]
}
ssm:UpdateInstanceInformation lets the SSM Agent on EC2 report its status to Systems Manager. The four ssmmessages:CreateControlChannel, ssmmessages:CreateDataChannel, ssmmessages:OpenControlChannel, ssmmessages:OpenDataChannel create, open the session’s channels. If you store session logs in S3 or CloudWatch Logs, or encrypt with KMS, you need permissions for that as well.
The person connecting (IAM user): for aws login
To use aws login, attach the AWS managed policy SignInLocalDevelopmentAccess. It contains just these two actions, so a custom policy can list the same:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"signin:AuthorizeOAuth2Access",
"signin:CreateOAuth2Token"
],
"Resource": "arn:aws:signin:*:*:oauth2/public-client/*"
}
]
}
The first lets you receive an authorization code from browser authentication; the second exchanges that code for a CLI token. A resource ending in localhost covers aws login on the same PC; remote covers aws login --remote, using a browser on another device. If you only ever use the same PC, you can narrow the resource to arn:aws:signin:*:*:oauth2/public-client/localhost.
The person connecting (IAM user): for Session Manager
There’s no AWS managed policy that fits the connecting side well. AmazonSSMFullAccess works, but it allows every Systems Manager operation, so I don’t recommend it outside test environments. Create a custom policy like this. Replace the account ID, region, instance ID with yours.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "StartPortForwardingToTarget",
"Effect": "Allow",
"Action": "ssm:StartSession",
"Resource": [
"arn:aws:ec2:ap-northeast-1:123456789012:instance/i-xxxxxxxxxxxxxxxxx",
"arn:aws:ssm:ap-northeast-1::document/AWS-StartPortForwardingSession"
],
"Condition": {
"BoolIfExists": {
"ssm:SessionDocumentAccessCheck": "true"
}
}
},
{
"Sid": "ManageOwnSessions",
"Effect": "Allow",
"Action": [
"ssm:TerminateSession",
"ssm:ResumeSession",
"ssmmessages:OpenDataChannel"
],
"Resource": "arn:aws:ssm:*:*:session/${aws:username}-*"
}
]
}
The first block limits what sessions can be started on to the target instance, the port forwarding document (AWS-StartPortForwardingSession). That document is provided by AWS, so its ARN has no account ID (it’s ::). The condition ssm:SessionDocumentAccessCheck makes the document permission check apply even when someone omits --document-name to open a normal shell session. With it, this user can’t get a shell on EC2; only port forwarding works.
The second block lets you terminate, resume only sessions you started. When you connect as an IAM user, the session ID is “IAM user name - random string”. In my environment too, the session ID in the SSM window started with my IAM user name. Hence the restriction with ${aws:username}.
The aws sts get-caller-identity used at the start of the batch is an API that always works without permissions, so it needn’t be in the policy.
Authenticate with aws login
aws login issues temporary credentials for the AWS CLI using the same credentials you sign in to the AWS Management Console with. Until now, using the CLI usually meant issuing an access key, saving it in the credentials file; that’s no longer needed.
aws login --profile aws-dev
For a new profile it first asks for a region. Then a browser opens automatically, while the terminal shows this (the screenshot is from running it via the batch, but running aws login directly looks the same):

The browser shows this screen. “Continue to sign in” goes to sign-in. If you’re already signed in to the console in another tab, “Refresh” uses that session.

Then sign in the same way you always do for the console: account ID, IAM user name, password.

After signing in, a profile like this is written to .aws\config:
[profile aws-dev] login_session = arn:aws:iam::123456789012:user/<user name>
The temporary credentials refresh automatically every 15 minutes, while the session itself lasts as long as set on the IAM side (up to 12 hours). When it expires, just run aws login again. Check that you’re logged in with:
aws sts get-caller-identity --profile aws-dev
First, connect by hand
Before making a batch file, confirm it connects manually. Port forwarding starts with this command; give the target instance ID to --target:
aws ssm start-session --target i-xxxxxxxxxxxxxxxxx --document-name AWS-StartPortForwardingSession --parameters "portNumber=3389,localPortNumber=13389" --profile aws-dev --region ap-northeast-1
When you see Port 13389 opened for sessionId ..., Waiting for connections..., it’s ready. Leave this window open, then connect Remote Desktop to localhost:13389:
mstsc /v:localhost:13389
It asks for credentials: enter the user name, password of the Windows Server on EC2. The target shows as localhost, but it actually reaches EC2. Check “Remember me” to skip this next time.

The local port is 13389 rather than 3389 so it doesn’t collide with the local PC’s own 3389. Any free number works.
A batch file that connects in one click
I put all the steps so far into one batch file. Just edit the settings at the top for your environment. Feel free to use it.
This batch leaves the aws login credentials on the PC. If you use a powerful account, or the PC also runs AI agents that execute commands, use the “version that leaves no credentials on the PC” further down instead.
@echo off
setlocal
rem ===== Settings =====
set PROFILE=aws-dev
set REGION=ap-northeast-1
set INSTANCE_ID=i-xxxxxxxxxxxxxxxxx
set LOCAL_PORT=13389
set REMOTE_PORT=3389
rem ====================
rem 1. Check credentials (run aws login if expired)
aws sts get-caller-identity --profile %PROFILE% --region %REGION% >nul 2>&1
if errorlevel 1 (
echo [INFO] Session expired. Running aws login...
aws login --profile %PROFILE% --region %REGION%
if errorlevel 1 (
echo [ERROR] aws login failed.
pause
exit /b 1
)
)
rem 2. Start port forwarding (skip if already listening)
netstat -an | findstr /r /c:"127.0.0.1:%LOCAL_PORT% .*LISTENING" >nul
if not errorlevel 1 (
echo [INFO] Port %LOCAL_PORT% already listening. Reusing existing session.
goto CONNECT
)
echo [INFO] Starting SSM port forwarding...
start "SSM-RDP %INSTANCE_ID% - close to disconnect" cmd /k aws ssm start-session --target %INSTANCE_ID% --document-name AWS-StartPortForwardingSession --parameters "portNumber=%REMOTE_PORT%,localPortNumber=%LOCAL_PORT%" --profile %PROFILE% --region %REGION%
rem 3. Wait for the port to open (max 30s)
set /a WAIT=0
:WAITLOOP
netstat -an | findstr /r /c:"127.0.0.1:%LOCAL_PORT% .*LISTENING" >nul
if not errorlevel 1 goto CONNECT
set /a WAIT+=1
if %WAIT% geq 30 (
echo [ERROR] Port %LOCAL_PORT% did not open. Check the SSM window for errors.
pause
exit /b 1
)
timeout /t 1 /nobreak >nul
goto WAITLOOP
rem 4. Connect via RDP
:CONNECT
echo [INFO] Connecting RDP to localhost:%LOCAL_PORT%
start "" mstsc /v:localhost:%LOCAL_PORT%
exit /b 0
The batch file’s messages, comments are in English to avoid garbled Japanese text from character encoding differences. As is, you don’t need to worry about encoding when saving in Notepad.
Double-click it and it does this, in order:
- Check authentication: if
aws sts get-caller-identityfails (= the session expired), it runsaws login. A browser opens; sign in to continue - Start port forwarding: starts the SSM session in a separate window. If 13389 is already listening, it reuses that
- Wait for the port: checks with
netstatthat 13389 is listening, giving up with an error after 30 seconds - Connect RDP: launches Remote Desktop with
mstsc /v:localhost:13389(why not an.rdpfile is explained below)
The SSM session keeps running in a separate “SSM-RDP …” window. Closing that window drops the connection, so close it when you’re done with RDP.
Gotcha 1: closing RDP says “An error occurred while saving to Default.rdp”
Connecting worked fine, but closing RDP showed an error saying an error occurred while saving to C:\Users\<user name>\Documents\Default.rdp.

When Remote Desktop is launched without an .rdp file, it writes the connection settings back to Default.rdp in the Documents folder on exit. That write was failing.
At first I suspected Default.rdp being a hidden file. Wrong guess: Remote Desktop always creates Default.rdp as hidden. In the Windows Defender event log (Event Viewer: Applications and Services Logs → Microsoft → Windows → Windows Defender → Operational), right at the time of the error, there was this record (event ID 1123):
C:\Windows\System32\mstsc.exe has been blocked from modifying %userprofile%\Documents\ by Controlled Folder Access.
The cause was Windows Security’s Controlled folder access, a ransomware protection that blocks unapproved apps from writing to folders like Documents. I had it on, so it was blocking Remote Desktop (mstsc.exe) too.
As a fix, I added mstsc.exe to the allowed apps. Open Windows Settings → Privacy & security → Windows Security, then choose “Virus & threat protection”. (Screenshots show the Japanese UI.)

Scroll down to “Ransomware protection”, then open “Manage ransomware protection”.

You can see “Controlled folder access” is on. Open “Allow an app through Controlled folder access” here.

From “Add an allowed app”, I picked C:\Windows\System32\mstsc.exe. Once mstsc.exe appears in the list, you’re set.

The error stopped after that. It only means the settings couldn’t be saved on exit; the connection itself isn’t affected. If you’d rather not change security settings, just pressing OK is harmless.
Gotcha 2: launching with an .rdp file warns “Unknown remote connection” every time
Before finding the cause above, I tried another workaround. Thinking “launching with an .rdp file shouldn’t write back to Default.rdp”, I made a dedicated .rdp file next to the batch file to open for connecting. The save error went away, but now a “Remote Desktop Connection security warning” appeared on every connection, reading “Caution: Unknown remote connection”, with the publisher shown as “Unknown publisher”.

This is a protection against phishing with malicious .rdp files, added in a Windows update in April 2026. Opening an unsigned .rdp file shows this warning every time, with resource sharing such as the clipboard off by default. There’s no longer a “Don’t ask me again” checkbox.
Signing the .rdp file would remove the warning, but that’s overkill for a personal batch file. In the end I dropped the .rdp file, going back to mstsc /v:localhost:13389, after fixing the save error at its root as described above. Launched with /v:, this warning doesn’t appear.
Connecting to several instances
To add targets, copy the batch file, then change:
INSTANCE_ID: the target instance IDLOCAL_PORT: if connecting simultaneously, a different number per instance (13390, etc.)
Bonus: a version that leaves no credentials on the PC
With the batch above, credentials from aws login stay cached in %USERPROFILE%\.aws\login\cache. They keep refreshing until the session expires (up to 12 hours), during which any program running as the same Windows user can use them.
I use a powerful account that I really only want used when I operate it by hand. But this PC sometimes has AI agents like Claude Code run commands. An AI agent could, as an extension of a task I gave it, operate AWS with those cached credentials. Leaving a powerful account’s credentials on the PC seemed like a bad idea.
So I made a version that runs aws logout right after the tunnel opens. SSM needs credentials only to start the session; a tunnel already open keeps working after logging out. In my test, RDP kept working normally after logout. Credentials now stay on the PC only for the few seconds between login and the tunnel opening.
Differences from the batch above:
- Once the tunnel opens,
aws logoutimmediately deletes the cached credentials - Remote Desktop is launched with
start /wait, waiting until the RDP window closes - After RDP closes, it finds the process listening on 13389 (Session Manager plugin) with
netstat -ano, ending it. That stops the tunnel, closing the SSM window, the batch window automatically - Since the SSM window always closes on its own, errors are written to a log file in the temp folder, shown in the batch window if the tunnel didn’t open
@echo off
setlocal
rem ===== Settings =====
set PROFILE=aws-dev
set REGION=ap-northeast-1
set INSTANCE_ID=i-xxxxxxxxxxxxxxxxx
set LOCAL_PORT=13389
set REMOTE_PORT=3389
rem ====================
set ERRLOG=%TEMP%\ssm-rdp-%LOCAL_PORT%-error.log
rem 1. Check credentials (run aws login if not logged in)
aws sts get-caller-identity --profile %PROFILE% --region %REGION% >nul 2>&1
if errorlevel 1 (
echo [INFO] Not logged in. Running aws login...
aws login --profile %PROFILE% --region %REGION%
if errorlevel 1 (
echo [ERROR] aws login failed.
pause
exit /b 1
)
)
rem 2. Start port forwarding (skip if already listening)
netstat -an | findstr /r /c:"127.0.0.1:%LOCAL_PORT% .*LISTENING" >nul
if not errorlevel 1 (
echo [INFO] Port %LOCAL_PORT% already listening. Reusing existing session.
goto TUNNEL_READY
)
echo [INFO] Starting SSM port forwarding...
rem The SSM window always closes when the tunnel ends. Errors are written to ERRLOG.
start "SSM-RDP %INSTANCE_ID%" cmd /c "aws ssm start-session --target %INSTANCE_ID% --document-name AWS-StartPortForwardingSession --parameters portNumber=%REMOTE_PORT%,localPortNumber=%LOCAL_PORT% --profile %PROFILE% --region %REGION% 2> "%ERRLOG%" & exit 0"
rem 3. Wait for the port to open (max 30s)
set /a WAIT=0
:WAITLOOP
netstat -an | findstr /r /c:"127.0.0.1:%LOCAL_PORT% .*LISTENING" >nul
if not errorlevel 1 goto TUNNEL_READY
set /a WAIT+=1
if %WAIT% geq 30 goto TUNNEL_FAILED
timeout /t 1 /nobreak >nul
goto WAITLOOP
:TUNNEL_FAILED
echo [ERROR] Port %LOCAL_PORT% did not open.
if exist "%ERRLOG%" type "%ERRLOG%"
aws logout --profile %PROFILE% >nul 2>&1
pause
exit /b 1
:TUNNEL_READY
rem 4. Log out right away. The open tunnel keeps working without the cached credentials.
echo [INFO] Tunnel is up. Logging out to remove cached credentials...
aws logout --profile %PROFILE% >nul 2>&1
rem 5. Connect via RDP and wait until the RDP window is closed
echo [INFO] Connecting RDP to localhost:%LOCAL_PORT%
echo [INFO] Do not close this window. It stops the tunnel when RDP is closed.
start "" /wait mstsc /v:localhost:%LOCAL_PORT%
rem 6. Stop the tunnel (the SSM window closes with it)
echo [INFO] RDP closed. Stopping the tunnel...
for /f "tokens=5" %%P in ('netstat -ano ^| findstr /r /c:"127.0.0.1:%LOCAL_PORT% .*LISTENING"') do taskkill /PID %%P /F >nul 2>&1
exit /b 0
Caveats:
- It logs out every time, so each connection needs a browser login. If you’re signed in to the console in another tab, “Refresh” is enough
- If you close the batch window while using RDP, cleanup doesn’t run, leaving the tunnel up (the credentials are already gone)
- If the network blips, the tunnel may not reconnect by itself. Just rerun the batch
- If a tunnel was already open on 13389, it gets stopped too when RDP closes
With a low-privilege account the first batch is enough. With a powerful account, or on a PC also running AI agents or other tools, I recommend this version.
Summary
Without opening 3389, without keeping an access key on the PC, a double-click now connects me to Windows Server on EC2. Compared with typing commands every time, the effort to connect has almost vanished.
As an advanced use, I also wrote how to open a private API Gateway behind the bastion in a local Edge browser with the same SSM port forwarding: Open a private API Gateway in local Edge without admin rights (in Japanese).
References: Login for AWS local development using console credentials - AWS CLI, Start a session - AWS Systems Manager, Create a custom IAM role for Session Manager - AWS Systems Manager, Sample IAM policies for Session Manager - AWS Systems Manager, SignInLocalDevelopmentAccess - AWS Managed Policy, Microsoft adds Windows protections for malicious Remote Desktop files - BleepingComputer


コメント