Windows – Random IT Utensils https://blog.adamfurmanek.pl IT, operating systems, maths, and more. Thu, 09 May 2024 09:54:43 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 Changing user password from command line in Windows https://blog.adamfurmanek.pl/2020/12/12/changing-user-password-from-command-line-in-windows/ https://blog.adamfurmanek.pl/2020/12/12/changing-user-password-from-command-line-in-windows/#respond Sat, 12 Dec 2020 09:00:20 +0000 https://blog.adamfurmanek.pl/?p=3599 Continue reading Changing user password from command line in Windows]]> If you search the Internet how to change the password in Windows using command line you’ll easily find command like one below:

net user name password

DO NOT USE IT! It doesn’t change the password, it resets it. When you reset the password this way, all things encrypted with user password are no longer accessible (unless you have the certificate backed up and want to go with manual decryption process). This includes EFS, user specific encrypted app configs, passwords, some Outlook settings etc.

So how do you do it? If you search a little longer you’ll probably find PowerShell commandlets for WinAPI methods to change AD password. Most likely this is not what you want as you have local user.

What works for me is the following C# code:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
{
	UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName);
	user.ChangePassword(oldPassword, newPassword);
}

You need to add reference to System.DirectoryServices. Works on Windows Server 2012 R2 with .NET Framework 4.5.

Some people suggest you should call user.Save(), however, it throws the following exception for me:

System.UnauthorizedAccessException: Access is denied.
   at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.SetInfo()
   at System.DirectoryServices.DirectoryEntry.CommitChanges()
   at System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(Principal p, StoreCtx storeCtx, GroupMembershipUpdater updateGroupMembership, NetCred credentials, AuthenticationTypes authTypes)
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.Update(Principal p)
   at System.DirectoryServices.AccountManagement.Principal.Save()

I don’t know if that’s needed but I do it anyway. What happens if you pass incorrect old password? You get

Unhandled Exception: System.DirectoryServices.AccountManagement.PasswordException: The specified network password is not correct.
 ---> System.Runtime.InteropServices.COMException: The specified network password is not correct.
   --- End of inner exception stack trace ---
   at System.DirectoryServices.AccountManagement.SDSUtils.ChangePassword(DirectoryEntry de, String oldPassword, String newPassword)
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.ChangePassword(AuthenticablePrincipal p, String oldPassword, String newPassword)
   at System.DirectoryServices.AccountManagement.PasswordInfo.ChangePassword(String oldPassword, String newPassword)
   at System.DirectoryServices.AccountManagement.AuthenticablePrincipal.ChangePassword(String oldPassword, String newPassword)

You can try wrapping this in some PowerShell code and you should be good.

]]>
https://blog.adamfurmanek.pl/2020/12/12/changing-user-password-from-command-line-in-windows/feed/ 0
Availability Anywhere Part 8 — Running interactive application on a remote server from shell https://blog.adamfurmanek.pl/2020/07/04/availability-anywhere-part-8/ https://blog.adamfurmanek.pl/2020/07/04/availability-anywhere-part-8/#comments Sat, 04 Jul 2020 08:00:33 +0000 https://blog.adamfurmanek.pl/?p=3373 Continue reading Availability Anywhere Part 8 — Running interactive application on a remote server from shell]]>

This is the eighth part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

Imagine that you’d like to run an interactive application on some remote server. This application should have access to UI and ideally pop-up in the session of logged-in user.
There is a psexec tool from Sysinternals and it can run applications remotely. However, it didn’t work for me (I guess some permission issues for remote shares) so I did it with PowerShell.

Run this:

$username = "DOMAIN\USER"
$pass = "PASSWORD"
$pass = convertto-securestring -asplaintext $pass -force
$cred = new-object System.Management.Automation.PSCredential -argumentlist $username, $pass
invoke-command -scriptblock { PATH_TO_SYSINTERNALS\.\psexec -accepteula -s -i 1 notepad.exe } -computername IP -credential $cred

In line 1 you specify username (with domain if needed).
In line 2 you provide a password.
Lines 3-4 create a secure password object.
Line 5 does the magic. First, it uses PowerShell Remoting to connect to the machine over IP with given credentials (see Part 3 how to configure PS Remoting). Next, it executes a command.
In the command we use psexec to run application interactively in session 1. We need to use -s parameter to run the app as a system account, otherwise it will not have an access to the UI. You may also use -u "DOMAIN\USER" -p "PASSWORD" of the session owner instead.

]]>
https://blog.adamfurmanek.pl/2020/07/04/availability-anywhere-part-8/feed/ 1
Availability Anywhere Part 7 — gpedit.msc on Windows Home https://blog.adamfurmanek.pl/2020/06/27/availability-anywhere-part-7/ https://blog.adamfurmanek.pl/2020/06/27/availability-anywhere-part-7/#comments Sat, 27 Jun 2020 08:00:20 +0000 https://blog.adamfurmanek.pl/?p=3352 Continue reading Availability Anywhere Part 7 — gpedit.msc on Windows Home]]>

This is the seventh part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

Multiple configuration tasks require you to open Group Policy Editor and do something. However, there is no gpedit.msc in Windows Home edition. However, you can install it using the following script (run as administrator):

@echo off
pushd "%~dp0"

dir /b %SystemRoot%\servicing\Packages\Microsoft-Windows-GroupPolicy-ClientExtensions-Package~3*.mum >List.txt
dir /b %SystemRoot%\servicing\Packages\Microsoft-Windows-GroupPolicy-ClientTools-Package~3*.mum >>List.txt

for /f %%i in ('findstr /i . List.txt 2^>nul') do dism /online /norestart /add-package:"%SystemRoot%\servicing\Packages\%%i"
pause

]]>
https://blog.adamfurmanek.pl/2020/06/27/availability-anywhere-part-7/feed/ 1
Availability Anywhere Part 6 — Task scheduler not running on next run date on Windows Home edition https://blog.adamfurmanek.pl/2020/06/20/availability-anywhere-part-6/ https://blog.adamfurmanek.pl/2020/06/20/availability-anywhere-part-6/#comments Sat, 20 Jun 2020 08:00:23 +0000 https://blog.adamfurmanek.pl/?p=3350 Continue reading Availability Anywhere Part 6 — Task scheduler not running on next run date on Windows Home edition]]>

This is the sixth part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

There is some bug with Task Scheduler not running the task on the next run date, similar to this question. In my case it was happening on Windows 10 Home edition on two different machines. I checked multiple solutions and none of them worked for me, the task was configured correctly but it wasn’t triggered.

I finally gave up and changed the script. Because I wanted to trigger a bat file every minute, I just changed the script. Previously I had a script VPN.bat which was triggered every minute to reconnect the VPN and configure the DNS. Now, I changed it to this:

:begin
start FULL_SCRIPT_PATH

timeout /t 30
goto begin

So I just run this script which works indefinitely and starts the other script. Now, it is important that the other script has explicit exit in it to avoid leaking cmd.exe instances.

Then I changed Task Scheduler to run the script on system startup. I also chose rerunning it every minute and not running in parallel, but it doesn’t matter as Task Scheduler doesn’t trigger it correctly.

]]>
https://blog.adamfurmanek.pl/2020/06/20/availability-anywhere-part-6/feed/ 1
UpdateOrchestrator waking up the machine https://blog.adamfurmanek.pl/2020/03/07/updateorchestrator-waking-up-the-machine/ https://blog.adamfurmanek.pl/2020/03/07/updateorchestrator-waking-up-the-machine/#comments Sat, 07 Mar 2020 09:00:08 +0000 https://blog.adamfurmanek.pl/?p=3255 Continue reading UpdateOrchestrator waking up the machine]]> Recently I was investigating machine waking up from sleep without any user interaction. It was a bit irritating because user was putting his PC to sleep and leaving it for a day just to notice in the evening that the machine woke up and was on for most of the time.

Event viewer showed this:

The system has returned from a low power state.

Sleep Time: ?2019?-?11?-?04T15:51:17.837661000Z
Wake Time: ?2019?-?11?-?04T16:09:31.442527100Z

Wake Source: Timer - Windows will execute 'NT TASK\Microsoft\Windows\UpdateOrchestrator\Universal Orchestrator Start' scheduled task that requested waking the computer.

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Microsoft-Windows-Power-Troubleshooter" Guid="{cdc05e28-c449-49c6-b9d2-88cf761644df}" /> 
  <EventID>1</EventID> 
  <Version>3</Version> 
  <Level>4</Level> 
  <Task>0</Task> 
  <Opcode>0</Opcode> 
  <Keywords>0x8000000000000000</Keywords> 
  <TimeCreated SystemTime="2019-11-04T16:09:31.658173400Z" /> 
  <EventRecordID>14127</EventRecordID> 
  <Correlation ActivityID="{0bdacabc-df50-4751-a5a5-8d03debed195}" /> 
  <Execution ProcessID="4416" ThreadID="17628" /> 
  <Channel>System</Channel> 
  <Computer>SEA-1800030347.ant.amazon.com</Computer> 
  <Security UserID="S-1-5-19" /> 
  </System>
- <EventData>
  <Data Name="SleepTime">2019-11-04T15:51:17.837661000Z</Data> 
  <Data Name="WakeTime">2019-11-04T16:09:31.442527100Z</Data> 
  <Data Name="SleepDuration">7800</Data> 
  <Data Name="WakeDuration">2942</Data> 
  <Data Name="DriverInitDuration">1650</Data> 
  <Data Name="BiosInitDuration">628</Data> 
  <Data Name="HiberWriteDuration">0</Data> 
  <Data Name="HiberReadDuration">0</Data> 
  <Data Name="HiberPagesWritten">0</Data> 
  <Data Name="Attributes">1879073024</Data> 
  <Data Name="TargetState">4</Data> 
  <Data Name="EffectiveState">4</Data> 
  <Data Name="WakeSourceType">6</Data> 
  <Data Name="WakeSourceTextLength">147</Data> 
  <Data Name="WakeSourceText">Windows will execute 'NT TASK\Microsoft\Windows\UpdateOrchestrator\Universal Orchestrator Start' scheduled task that requested waking the computer.</Data> 
  <Data Name="WakeTimerOwnerLength">52</Data> 
  <Data Name="WakeTimerContextLength">18</Data> 
  <Data Name="NoMultiStageResumeReason">0</Data> 
  <Data Name="WakeTimerOwner">\Device\HarddiskVolume4\Windows\System32\svchost.exe</Data> 
  <Data Name="WakeTimerContext">SystemEventsBroker</Data> 
  <Data Name="CheckpointDuration">108</Data> 
  </EventData>
  </Event>

So it looks like there was some update task waking the computer. After opening the Task Scheduler we could see this:

There are two important things you can see (even though screenshot is in Polish). First, owner of the task is NT SYSTEM. Second, it is scheduled to run at 8:58 AM.

So we know why the machine was waking up. How can we disable the task? Starting Task Scheduler as an administrator didn’t allow us to disable the task.

The thing is: Administrator is not the most powerful account in Windows. SYSTEM account has more privileges and we need to use it to disable the task. How do we run Task Scheduler as NT SYSTEM?

I typically use psexec from Sysinternals. Just run this command:

psexec -s -i mmc.exe

This opens management console. Add snap-in for Task Scheduler and you are good to go. Now you can disable the task and see that it solves the issue.

]]>
https://blog.adamfurmanek.pl/2020/03/07/updateorchestrator-waking-up-the-machine/feed/ 1
Availability Anywhere Part 5 — Various remote connection things https://blog.adamfurmanek.pl/2019/12/21/availability-anywhere-part-5/ https://blog.adamfurmanek.pl/2019/12/21/availability-anywhere-part-5/#comments Sat, 21 Dec 2019 09:00:53 +0000 https://blog.adamfurmanek.pl/?p=3184 Continue reading Availability Anywhere Part 5 — Various remote connection things]]>

This is the fifth part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

Today I include some various notes around remote connectivity which I was fixing over the years. Nothing new here, things you can easily find on the Internet. This is mostly dump of my Evernote.

How to configure VPN in Windows Server 2012 (for Azure)

Based mostly on Stack Overflow answer

Server Role

1. Click on Server Manager -> Manage -> "Add Roles and Features"
2. Add “Remote Access”, include VPN and Routing (needed for NAT) role services and restart
3. Click on Server Manager -> Notifications -> "Open the Getting Started Wizard"
4. Select “Deploy VPN only”

Server Certificate

1. Open an elevated CMD prompt
2. Use SelfSSL (IIS6 Resource Kit, custom install only this component) to generate an SSL certificate for the SSTP:

selfssl.exe /N:cn=CN/V:3650

(3650 == 10 years, “CN” represents the fully-qualified domain name, FQDN)
3. Confirm prompt with “y”, ignore metabase error (if it appears)
4. Run mmc.exe, add snap-in for Certificates -> Computer account
5. Click on Personal -> Certificates
6. Right-click on the CN certificate, then on All Tasks -> Export, include private keys and protect with password

Server RRAS

1. Run Routing and Remote Access (RRAS) tool
2. Right-click on the server and then on “Configure and Enable RRAS”
3. Choose “Custom configuration”, select “VPN access” and NAT
4. Right-click on the server and then on Properties -> Security
5. Select the CN certificate
6. Click on the IPv4 tab
7. Enter a “Static address pool” for the number of clients, e.g.: 192.168.1.1 – 192.168.1.20 (otherwise the connection will fail with error 720), then close the dialog
8. Don’t enter a range that is too short. The OS keeps a lock on a used IP address for a while, so reconnecting often or from multiple devices may use up the pool and the connection will fail with error 0x8007274C
9. Expand the IPv4 node, then right-click on NAT, then on “New Interface”, select the external interface (e.g. “Ethernet 2”)
10. Click on “Public interface connected to the Internet” and check “Enable NAT on this interface”

Server User

1. Open “Computer Management” console
2. Click on “Local Users and Groups”, then on Users, double click on your account
3. Click on Dial-in and change “Network Access Permission” to “Allow access”

Client Certificate

1. Install exported server certificate to client’s “Local Machine” store
2. Click on “Place all certificates in the following store”, then on Browse
3. Select “Trusted Root Certificate Authorities”, if you store the certificate in the personal store, the connection will fail with error 0x800B0109

Client Connection

1. Go to Network and Sharing Center, click on “Setup a new connection or network”
2. Select “Connect to a workplace”, then VPN
3. Enter CN, name and create
4. Click on Network tray icon
5. Right-click on new VPN connection, then show properties
6. Click on Security, set VPN type to SSTP and allow only MS-CHAP v2
7. Connect using same credentials used to create the VM and for RDP
8. Test your internet connectivity
9. Use a web site that shows your external IP, it should be an IP from the Azure datacenter

Make sure to unblock ports 1701 (L2TP UDP), 500 (IPsec UDP) and 4500 (IKEv2 UDP).

L2TP over IPsec

1. On the Server, open the “Windows Firewall with Advanced Security”, create a rule called IKEv2 and allow inbound traffic to UDP port 4500 (otherwise the connection will fail with error 809)
2. Using the RRAS tool, right-click on the server and then on Properties -> Security
3. Check “Allow custom IPsec policy for L2TP/IKEv2 connection” and enter a preshared key
4. On the client, right-click on new VPN connection, then show properties
5. Click on Security, then on click on “Advanced settings” and enter the same preshared key

Fix for Windows 7 L2TP

Add to registry HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PolicyAgent\AssumeUDPEncapsulationContextOnSendRule as DWORD with value 2.

Fix for Windows XP L2TP

Add to registry HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\IPsec as DWORD with value 2.

Split tunneling

On client machine disable using default gateway in remote network (in connection settings). Or with PS

Set-VpnConnection -Name vpn-connection-name -SplitTunneling $true

Or using rasdial settings — go to c:\ProgramData\Microsoft\Network\Connections\Pbk\rasphone.pbk and change IpPrioritizeRemote parameter. If you configured connection as for user only (not for global machine), rasphone.pbk will be somewhere in Appdata.

Port forwarding on server

netsh interface portproxy add v4tov4 listenport=12345 connectport=443 connectaddress=192.168.1.1

Fixing FTP on server

Disable Application Level Gateway service otherwise you won’t be able to connect to FTP with split tunneling enabled.

Fixing error 812 – the authentication method used by the server to verify your username and password may not match the authentication method configured in your connection profile

Open the routing and remote access management console.
Right-click on “Remote Access Logging and Policies” then click on Launch NPS.
Click on “Network Policies” in the left pane Right click on the “Connections to Microsoft Routing and Remote Access server” policy in the right pane and select properties.
Change from “Deny Access” to “Grant Access” on the radio buttons in the middle.
Hit Apply.

Logs

See in C:\windows\system32\logfiles

Configuring RemoteApp Terminal Services

Use RemoteApp Tool

Just make sure to fix full address:s: and alternate full address:s: in generated RDP file (replace hostname with IP address used over VPN).

Configuring firewall for most useful ports

Open those ports for outgoing connections on the client (I open both UDP and TCP):

22 SSH
47 GRE
53 DNS
67 DHCP
68 DHCP
80 HTTP
443 HTTPS
500 IPSEC
554 AirPlay
1701 L2TP
3389 MSTSC
4500 IKEv2
5289 Bonjour
5353 Bonjour/AirPlay
49159 Bonjour/AirPlay
49163 Bonjour/AirPlay
53319 MSTSC

Range rule is:

1-21, 23-46, 48-52, 54-66, 69-79, 81-442, 444-499, 501-553, 555-1700, 1702-3388, 3390-4499, 4501-5288, 5290-5352, 5354-7235, 7237-7249, 7251-49158, 49160-49162, 49164-53318, 53320-65535

Bonjour/AirPlay may be for Miracast as well (I’m not sure which are used exactly).

OpenSSH configuration

Use Win32-OpenSSH.

Changing network profile to private

To change the network type please do the following:
Hit Winkey + R to open Run prompt and type gpedit.msc
Navigate to: Computer Configuration | Windows Settings | Security Setting | Network List Manager Policies
Choose your Network name from the right pane. In my case network name was Network 2
Go to Network Location tab and change the Location type from Not configured to Private.

Or via registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles
Category 0 means public, 1 means private, 2 means domain. Also add CategoryType and set it to 0.

Multiple RDP sessions

Go to HKLM\System\CurrentControlSet\Control\Terminal Server\ and set

fDenyTSConnections (DWORD) = 0
fSingleSessionPerUser (DWORD) = 0

Installing RDP client in CentOS

yumdownloader rdesktop
rpm2cpio rdesktop... | cpio -id

]]>
https://blog.adamfurmanek.pl/2019/12/21/availability-anywhere-part-5/feed/ 1
Availability Anywhere Part 4 — Fixing LogonUi hang https://blog.adamfurmanek.pl/2019/12/14/availability-anywhere-part-4/ https://blog.adamfurmanek.pl/2019/12/14/availability-anywhere-part-4/#comments Sat, 14 Dec 2019 09:00:59 +0000 https://blog.adamfurmanek.pl/?p=3180 Continue reading Availability Anywhere Part 4 — Fixing LogonUi hang]]>

This is the fourth part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

Sometimes when I RDP into other machine and forget to close the connection gently (I put my client to sleep or my VPN gets terminated), I cannot log into the machine anymore. It hangs on the login screen with picture like this:

I can log into the machine using RemoteApp Terminal Services, SSH into it or connect over PS Remoting but I cannot log into existing session opened via RDP previously.

The reason for that is LogonUi.exe process which hangs. I believe this has something to do with HP fingerprint reader but I didn’t confirm that.

So what to do in case of an error like this? Simply open another session using RemoteApp TS and run CMD (or SSH/PS Remote into the machine) and try killing the process with

taskkill /F /IM LogonUi.exe

Then you should be able to log into the session again. Obviously, this requires some alternative connection to the machine but this was covered in last weeks.

]]>
https://blog.adamfurmanek.pl/2019/12/14/availability-anywhere-part-4/feed/ 1
Availability Anywhere Part 3 — How to enable PowerShell remoting in Windows https://blog.adamfurmanek.pl/2019/12/07/availability-anywhere-part-3/ https://blog.adamfurmanek.pl/2019/12/07/availability-anywhere-part-3/#comments Sat, 07 Dec 2019 09:00:28 +0000 https://blog.adamfurmanek.pl/?p=3177 Continue reading Availability Anywhere Part 3 — How to enable PowerShell remoting in Windows]]>

This is the third part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

Today we will enable PowerShell Remoting in Windows. This sounds like a trivial task (you can google up an “easy” solution) but every time I’m doing that it happens that I need more and more commands because there are more and more settings to tweak. This note tries to summarize everything I captured over the last 10 years.

Server configuration — for receiving connections

First, run elevated PS and run this:

enable-psremoting -force -SkipNetworkProfileCheck -confirm

Confirm everything and this in theory enables PS Remoting. It’s is not enough, though, because you need to allow multiple other things to get connections over IP (not using domain name) and without encryption (which we take care of using tunneling or VPN). Start with this:

netsh advfirewall firewall add rule name='PSRemoting HTTP' dir=in action=allow protocol=TCP localport=5985
netsh advfirewall firewall add rule name='PSRemoting HTTPS' dir=in action=allow protocol=TCP localport=5986

This configures your firewall. Now, you want to enable Windows Remote Management (WinRM). Open gpedit.msc, browse to Computer Configuration > Administrative Templates > Windows Components > Windows Remote Management (WinRM) > WinRM Service and enable Open the Allow Remote Server management through WinRM policy setting. Set filters to * (unless you need something specific there).

Next, enable firewall rules for all profiles. In gpedit.msc browse to Computer Configuration> Administrative Templates > Network > Network Connections > Windows Firewall > Domain Profile and open Windows Defender Firewall: Define inbound port exceptions policy setting. Enable it, click Show button and add those port exceptions:

5985:TCP:*:enabled:WSMan
5986:TCP:*:enabled:WSMan

Finally, you need to give permissions for particular users to connect to the machine. Run

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

and give permissions to users of your choice.

To verify your setting, run

winrm get winrm/config/listener?Address=*+Transport=HTTP

and you should get something like

Listener [Source="GPO"]
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = 127.0.0.1, 169.254.148.232, 169.254.170.254, , ::1, fe80::24a9:613:3ca1:6de8%4

Client — for connecting to other machine over HTTP and IP address

You need to add trusted hosts using elevated PS:

Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*"

Now you can connect using

etsn -computername IP_ADDRESS -port 5985 -credential DOMAIN\USER

This makes an unencrypted connection using IP address. Obviously, you want to open this connection over VPN/SSH tunnel. If you want encryption, go with

etsn -computername IP_ADDRESS -usessl -port 5986 -credential DOMAIN\USER

]]>
https://blog.adamfurmanek.pl/2019/12/07/availability-anywhere-part-3/feed/ 1
Availability Anywhere Part 2 — Connecting to VPN automatically in Windows https://blog.adamfurmanek.pl/2019/11/30/availability-anywhere-part-2/ https://blog.adamfurmanek.pl/2019/11/30/availability-anywhere-part-2/#comments Sat, 30 Nov 2019 09:00:49 +0000 https://blog.adamfurmanek.pl/?p=3174 Continue reading Availability Anywhere Part 2 — Connecting to VPN automatically in Windows]]>

This is the second part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows

Last week we saw how to configure automatic SSH tunnel connection. Today we will go with VPN.

I am using built-in VPN provider (SSTP and L2TP) supported by rasdial.

First, configure your VPN (using either PS or GUI). It doesn’t matter which options you choose, just make sure it works and can connect correctly.
Next, it’s time to set up a script for automatically connecting to VPN:

ping -n 1 YOUR_VPN_SERVER_IP | find "time=" > NUL
if not errorlevel 1 (
	netsh interface IPv4 set dnsserver "Wi-Fi" static 0.0.0.0 both
	netsh interface IPv4 set dnsserver "Local Area Connection" static 0.0.0.0 both
	exit
)

rasdial VPN_NAME /disconnect
netsh interface IPv4 set dnsserver "Wi-Fi" source="dhcp"
netsh interface IPv4 set dnsserver "Local Area Connection" source="dhcp"

rasdial VPN_NAME USERNAME PASSWORD

ping -n 1 YOUR_VPN_SERVER_IP | find "time=" > NUL
if not errorlevel 1 (
	netsh interface IPv4 set dnsserver "Wi-Fi" static 0.0.0.0 both
	netsh interface IPv4 set dnsserver "Local Area Connection" static 0.0.0.0 both
)

This script does multiple things. First, in lines 1 to 6 I check if I am already connected. I am running this script frequently (each minute) and I want to disable DNS leaking so I set DNS Server to invalid address for regular network interfaces when I’m connected. If everything is okay, I exit in line 5.

If I cannot reach the server then I disconnect (line 8), I restore DHCP for DNS resolution and then in line 12 I try connecting. Finally, I check if I’m connected and then reset DNS again.

This configuration works for “regular” networks (like at home or in my office) and also for those hotel WiFis requiring authentication via browser. If it detects it cannot connect to VPN server then it resets settings to DHCP and then I can authenticate in the browser.

Now, you need to have task for task scheduler. This is almost the same as last week only this time I’m running it as a user in which I log into the machine. Just keep in mind that when you change your password then you need to go to task scheduler, open settings of the task, close them and enter new password, then restart your computer.

]]>
https://blog.adamfurmanek.pl/2019/11/30/availability-anywhere-part-2/feed/ 1
Availability Anywhere Part 1 — Connecting to SSH tunnel automatically in Windows https://blog.adamfurmanek.pl/2019/11/23/availability-anywhere-part-1/ https://blog.adamfurmanek.pl/2019/11/23/availability-anywhere-part-1/#comments Sat, 23 Nov 2019 09:00:25 +0000 https://blog.adamfurmanek.pl/?p=3169 Continue reading Availability Anywhere Part 1 — Connecting to SSH tunnel automatically in Windows]]>

This is the first part of the Availability Anywhere series. For your convenience you can find other parts using the links below:
Part 1 — Connecting to SSH tunnel automatically in Windows
Part 2 — Connecting to VPN automatically in Windows
Part 3 — How to enable PowerShell remoting in Windows
Part 4 — Fixing LogonUi hang
Part 5 — Various remote connection things
Part 6 — Task scheduler not running on next run date on Windows Home edition
Part 7 — gpedit.msc on Windows Home
Part 8 — Running interactive application on a remote server from shell
Part 9 — Poor man’s channel bonding for RDP
Part 10 — Slightly better poor man’s channel bonding for RDP
Part 11 — Keeping a channel fresh
Part 12 — FileProxy for avoiding VPN without split tunneling (also known as TCP over File System)
Part 13 — Optimizing FileProxy
Part 14 — TCP over Named Pipe
Part 15 — TCP over Serial Port
Part 16 — Forwarding port from host to docker
Part 17 — Splitting physical monitor into multiple
Part 18 — Binding same port for multiple docker containers
Part 19 — Banning RDP and SSH attacks
Part 20 — Nested full-tunnel VPN in another full-tunnel VPN with force tunnel mode
Part 21 — Fixed mstsc.exe broken UI
Part 22 — Customer Experience Improvement Program restarts
Part 23 — RDP over VR goggles with no PCVR
Part 24 — Make RDP retain position of windows and stop moving them around
Part 25 — Supercharge your VR experience
Part 26 — Working remotely like a pro
Availability Anywhere Part 27 — Tools for remote work from laptops and XR/VR/AR

Let’s say that you want to configure reverse tunnel for connecting to your laptop computer. How to do that so it is started automatically when you boot your machine and it is reliable? In this post I will describe my configuration which I use for almost 10 years now. It is old and I bet there are better solutions available but I wanted to use something built into Windows with minimal dependencies needed. I am using this since Windows 7 and it still works. It opens tunnels for me so I can RDP into my machine from any place in the world.

Kitty

First, you need to have an SSH tunnel. For that you can use Kitty, a fork of Putty which gives some more options. It can save password (if you want to go with it instead of keys) and has options for restarting.

Basically, I use this configuration:

DisableAltGr\0\
PortKnocking\\
SCPAutoPwd\0\
ACSinUTF\0\
Comment\\
CtrlTabSwitch\0\
Password\passwordHash\
ForegroundOnBell\0\
SaveWindowPos\0\
WindowState\0\
TermYPos\-1\
TermXPos\-1\
LogTimeRotation\0\
Folder\Default\
AutocommandOut\\
Autocommand\\
LogTimestamp\\
AntiIdle\test\
ScriptfileContent\\
Scriptfile\\
SFTPConnect\\
IconeFile\\
Icone\1\
SaveOnExit\0\
Fullscreen\0\
Maximize\0\
SendToTray\0\
TransparencyValue\0\
zDownloadDir\C%3A%5C\
szOptions\-e%20-v\
szCommand\sz\
rzOptions\-e%20-v\
rzCommand\rz\
CygtermCommand\\
Cygterm64\0\
CygtermAutoPath\1\
CygtermAltMetabit\0\
HyperlinkRegularExpression\(((https%3F%7Cftp)%3A%5C%2F%5C%2F)%7Cwww%5C.)(([0-9]+%5C.[0-9]+%5C.[0-9]+%5C.[0-9]+)%7Clocalhost%7C([a-zA-Z0-9%5C-]+%5C.)%2A[a-zA-Z0-9%5C-]+%5C.(com%7Cnet%7Corg%7Cinfo%7Cbiz%7Cgov%7Cname%7Cedu%7C[a-zA-Z][a-zA-Z]))(%3A[0-9]+)%3F((%5C%2F%7C%5C%3F)[^%20%22]%2A[^%20,;%5C.%3A%22%3E)])%3F\
HyperlinkRegularExpressionUseDefault\1\
HyperlinkBrowser\\
HyperlinkBrowserUseDefault\1\
HyperlinkUseCtrlClick\0\
HyperlinkUnderline\1\
FailureReconnect\1\
WakeupReconnect\1\
ScriptHalt\\
ScriptWait\\
ScriptTimeout\30\
ScriptExcept\0\
ScriptEnable\0\
ScriptCRLF\1\
ScriptCondUse\0\
ScriptCondLine\%3A\
ScriptCharDelay\0\
ScriptLineDelay\0\
ScriptMode\0\
ScriptFileName\\
SSHManualHostKeys\\
ConnectionSharingDownstream\1\
ConnectionSharingUpstream\1\
ConnectionSharing\0\
WindowClass\\
SerialFlowControl\1\
SerialParity\0\
SerialStopHalfbits\2\
SerialDataBits\8\
SerialSpeed\9600\
SerialLine\COM1\
ShadowBoldOffset\1\
ShadowBold\0\
WideBoldFontHeight\2048\
WideBoldFontCharSet\5276560\
WideBoldFontIsBold\3866820\
WideBoldFont\\
WideFontHeight\2048\
WideFontCharSet\5276484\
WideFontIsBold\3866820\
WideFont\\
BoldFontHeight\2048\
BoldFontCharSet\5276408\
BoldFontIsBold\3866820\
BoldFont\\
ScrollbarOnLeft\0\
LoginShell\1\
StampUtmp\1\
BugChanReq\0\
BugWinadj\0\
BugOldGex2\0\
BugMaxPkt2\0\
BugRekey2\0\
BugPKSessID2\0\
BugRSAPad2\0\
BugDeriveKey2\0\
BugHMAC2\0\
BugIgnore2\0\
BugRSA1\0\
BugPlainPW1\0\
BugIgnore1\0\
PortForwardings\R5524=localhost%3A3389,R5534=localhost%3A5985,R5544=localhost%3A5986,R5554=localhost%3A22\
RemotePortAcceptAll\1\
LocalPortAcceptAll\1\
X11AuthFile\\
X11AuthType\1\
X11Display\\
X11Forward\0\
BlinkText\0\
BCE\1\
LockSize\0\
EraseToScrollback\1\
ScrollOnDisp\1\
ScrollOnKey\0\
ScrollBarFullScreen\0\
ScrollBar\1\
CapsLockCyr\0\
Printer\\
UTF8Override\1\
CJKAmbigWide\0\
LineCodePage\UTF-8\
Wordness224\2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2\
Wordness192\2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2\
Wordness160\1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\
Wordness128\1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\
Wordness96\1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1\
Wordness64\1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2\
Wordness32\0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1\
Wordness0\0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\
MouseOverride\1\
RectSelect\0\
MouseIsXterm\0\
PasteRTF\0\
RawCNP\0\
Colour33\187,187,187\
Colour32\0,0,0\
Colour31\187,187,187\
Colour30\0,187,187\
Colour29\187,0,187\
Colour28\0,0,187\
Colour27\187,187,0\
Colour26\0,187,0\
Colour25\187,0,0\
Colour24\0,0,0\
Colour23\0,0,0\
Colour22\187,187,187\
Colour21\255,255,255\
Colour20\187,187,187\
Colour19\85,255,255\
Colour18\0,187,187\
Colour17\255,85,255\
Colour16\187,0,187\
Colour15\85,85,255\
Colour14\0,0,187\
Colour13\255,255,85\
Colour12\187,187,0\
Colour11\85,255,85\
Colour10\0,187,0\
Colour9\255,85,85\
Colour8\187,0,0\
Colour7\85,85,85\
Colour6\0,0,0\
Colour5\0,255,0\
Colour4\0,0,0\
Colour3\85,85,85\
Colour2\0,0,0\
Colour1\255,255,255\
Colour0\187,187,187\
SelectedAsColour\0\
UnderlinedAsColour\0\
BoldAsColourTest\1\
DisableBottomButtons\1\
WindowHasSysMenu\1\
WindowMaximizable\1\
WindowMinimizable\1\
WindowClosable\1\
BoldAsColour\1\
Xterm256Colour\1\
ANSIColour\1\
TryPalette\0\
UseSystemColours\0\
FontVTMode\4\
FontQuality\0\
FontHeight\10\
FontCharSet\0\
FontIsBold\0\
Font\Courier%20New\
TermHeight\24\
TermWidth\80\
WinTitle\\
WinNameAlways\1\
DisableBidi\0\
DisableArabicShaping\0\
CRImpliesLF\0\
LFImpliesCR\0\
AutoWrapMode\1\
DECOriginMode\0\
ScrollbackLines\200\
BellOverloadS\5000\
BellOverloadT\2000\
BellOverloadN\5\
BellOverload\1\
BellWaveFile\\
BeepInd\0\
Beep\1\
BlinkCur\0\
CurType\0\
WindowBorder\1\
SunkenEdge\0\
HideMousePtr\0\
FullScreenOnAltEnter\0\
AlwaysOnTop\0\
Answerback\KiTTY\
LocalEdit\2\
LocalEcho\2\
TelnetRet\1\
TelnetKey\0\
CtrlAltKeys\1\
ComposeKey\0\
AltOnly\0\
AltSpace\0\
AltF4\1\
NetHackKeypad\0\
ApplicationKeypad\0\
ApplicationCursorKeys\0\
NoRemoteCharset\0\
NoDBackspace\0\
RemoteQTitleAction\1\
NoRemoteClearScroll\0\
NoRemoteWinTitle\0\
NoAltScreen\0\
NoRemoteResize\0\
NoMouseReporting\0\
NoApplicationCursors\0\
NoApplicationKeys\0\
LinuxFunctionKeys\0\
RXVTHomeEnd\0\
BackspaceIsDelete\1\
PassiveTelnet\0\
RFCEnviron\0\
RemoteCommand\\
PublicKeyFile\\
SSH2DES\0\
LogHost\\
SshProt\3\
SshNoShell\0\
GSSCustom\\
GSSLibs\gssapi32,sspi,custom\
AuthGSSAPI\1\
AuthKI\1\
AuthTIS\0\
SshBanner\1\
SshNoAuth\0\
RekeyBytes\1G\
RekeyTime\60\
HostKey\ed25519,ecdsa,rsa,dsa,WARN\
KEX\ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1\
Cipher\aes,chacha20,blowfish,3des,WARN,arcfour,des\
ChangeUsername\0\
GssapiFwd\0\
AgentFwd\0\
TryAgent\1\
Compression\0\
NoPTY\0\
LocalUserName\\
UserNameFromEnvironment\0\
UserName\afish\
Environment\\
ProxyLogToTerm\1\
ProxyTelnetCommand\connect%20%25host%20%25port%5Cn\
ProxyPassword\\
ProxyUsername\\
ProxyPort\80\
ProxyHost\proxy\
ProxyMethod\0\
ProxyLocalhost\0\
ProxyDNS\1\
ProxyExcludeList\\
AddressFamily\0\
TerminalModes\CS7=A,CS8=A,DISCARD=A,DSUSP=A,ECHO=A,ECHOCTL=A,ECHOE=A,ECHOK=A,ECHOKE=A,ECHONL=A,EOF=A,EOL=A,EOL2=A,ERASE=A,FLUSH=A,ICANON=A,ICRNL=A,IEXTEN=A,IGNCR=A,IGNPAR=A,IMAXBEL=A,INLCR=A,INPCK=A,INTR=A,ISIG=A,ISTRIP=A,IUCLC=A,IUTF8=A,IXANY=A,IXOFF=A,IXON=A,KILL=A,LNEXT=A,NOFLSH=A,OCRNL=A,OLCUC=A,ONLCR=A,ONLRET=A,ONOCR=A,OPOST=A,PARENB=A,PARMRK=A,PARODD=A,PENDIN=A,QUIT=A,REPRINT=A,START=A,STATUS=A,STOP=A,SUSP=A,SWTCH=A,TOSTOP=A,WERASE=A,XCASE=A\
TerminalSpeed\38400,38400\
TerminalType\xterm\
TCPKeepalives\1\
TCPNoDelay\1\
PingIntervalSecs\10\
PingInterval\0\
WarnOnClose\0\
CloseOnExit\2\
PortNumber\22\
Protocol\ssh\
SSHLogOmitData\0\
SSHLogOmitPasswords\1\
LogFlush\1\
LogFileClash\-1\
LogType\0\
LogFileName\putty.log\
HostName\host\
Present\1\

It’s quite big but there are only few important things which you need to configure:
In Window -> Behaviour deselect “Warn before closing window” to be sure.
In Connection set a keepalive to something like 10 and anti-idle string to something like test. Also, select to “reconnect on system wakeup” and “reconnect on connection failure”.
In Connection -> Data choose your username and password.
In Connection -> SSH -> Tunnels choose your ports. I am forwarding 3389 (RDP), 5985 and 5986 (PS Remoting), 22 (OpenSSH).
In Session choose “Always” for “Close window on exit”.

Make sure to connect manually at least once to accept the key and you should be good to go.

Task scheduler

Now you need to run this thing automatically on system start. I am using this script:

:start
taskkill /F /IM kitty.exe
kitty -load profile -send-to-tray -log putty.log 
goto start

Save this as a bat file.
Next, I noticed that sometimes I cannot RDP to my machine using the same user which actually runs this script. So I create new user in the system (it can be a local one, no need to use domain one), give it permissions to kitty and session file, run session (to accept the key). Then I use this Task scheduler:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2010-01-01T00:00:00.0000000</Date>
    <Author>Author</Author>
  </RegistrationInfo>
  <Triggers>
    <BootTrigger>
      <Enabled>true</Enabled>
    </BootTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>Author</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>false</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
    <RestartOnFailure>
      <Interval>PT1M</Interval>
      <Count>999</Count>
    </RestartOnFailure>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>starttunnel.bat</Command>
    </Exec>
  </Actions>
</Task>

Write this as an XML file, import to task scheduler, adjust paths, enter password for Author user and restart the operating system. Make sure you enable history logging in Task Scheduler to have some logging in case of errors.

]]>
https://blog.adamfurmanek.pl/2019/11/23/availability-anywhere-part-1/feed/ 14