Thread View: alt.comp.microsoft.windows
5 messages
5 total messages
Started by Maria Sophia
Tue, 03 Nov 2026 17:07
PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
Author: Maria Sophia
Date: Tue, 03 Nov 2026 17:07
Date: Tue, 03 Nov 2026 17:07
44 lines
3487 bytes
3487 bytes
PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
More and more, email/social media/news sites balk at some Tor exit nodes.
So I set it to US exit nodes only.
But there was debugging necessary, so to help others, here's what I did.
The one step is to set this in the torrc file:
C:\> gvim "C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\torrc"
ExitNodes {us}
StrictNodes 1
But these were the (simplified) steps that worked:
1. Close tor browser & find & kill any and all related processes
C:\> tasklist | findstr /i "firefox tor"
C:\> taskkill /f /im tor.exe /im firefox.exe
2. Tor caches old routing paths and consensus lists.
Deleting these forces it to pull a fresh node list:
C:\> del "C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\cached-microdescs"
C:\> del "C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\cached-microdesc-consensus"
Note: I never use plurals, spaces, nor more than 8 character naming.
a. Software goes in: C:\software\browser\tor\.
b. Apps go in: C:\app\browser\tor\.
c. Menus go in: C:\menu\browser\tor\.
Everything after that, is put there by the developer.
3. Add the directive to exit from US nodes only to the torrc file:
C:\> gvim "C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\torrc"
ExitNodes {us}
StrictNodes 1
4. Test using debug mode (which only outputs to standard out):
C:\> "C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Tor\tor.exe" -f "C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\torrc" --Log "notice stdout"
5. Launch the tor browser normally:
"C:\app\browser\tor\Tor Browser\Start Tor Browser.lnk"
TARGET: "C:\app\browser\tor\Tor Browser\Browser\firefox.exe"
STARTIN: "C:\app\browser\tor\Tor Browser"
HINT: Write the location of the torrc file into the link comment
so the future you won't waste time looking for it to edit.
--
Just one person on Usenet paying it forward so all benefit daily.
Re: PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
Author: Maria Sophia
Date: Wed, 04 Nov 2026 16:48
Date: Wed, 04 Nov 2026 16:48
35 lines
3487 bytes
3487 bytes
Given the goal is to use one exit node, if possible, per social media web
site, I ran a search for potential USA exit nodes to use per web site.
<https://metrics.torproject.org/>
<https://metrics.torproject.org/rs.html#search>
<https://metrics.torproject.org/rs.html#search/country:us%20flag:exit>
Let's just take a few of them, by way of example for others to benefit.
<https://metrics.torproject.org/rs.html#details/688604204AF0C0473DFFA8CD2E186D1EEAEE6916>
Fingerprint $688604204AF0C0473DFFA8CD2E186D1EEAEE6916
<https://metrics.torproject.org/rs.html#details/B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C>
Fingerprint $B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C
<https://metrics.torproject.org/rs.html#details/BD610AAEAE179EC259B022A178A75C70042407FB>
Fingerprint $BD610AAEAE179EC259B022A178A75C70042407FB
<https://metrics.torproject.org/rs.html#details/9C7B1DB2C5520B21E181EB945A01E9ABA42654A2>
Fingerprint $9C7B1DB2C5520B21E181EB945A01E9ABA42654A2
This line allows the Tor browser to pick among those exit nodes.
ExitNodes $688604204AF0C0473DFFA8CD2E186D1EEAEE6916,$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C,$BD610AAEAE179EC259B022A178A75C70042407FB,$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2
Unfortunately, the following flaws need to be overcome:
1. You can't trivially choose an exit node per web site
2. The exit nodes end up being random (the order listed doesn't matter)
3. If all of those exit nodes are down, it won't connect
3. If we add "us", it doesn't first prefer the listed fingerprinted nodes
ExitNodes {us},$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C,$BD610AAEAE179EC259B022A178A75C70042407FB,$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2
I can write code to ask what web site I'm going to, and then insert
a given USA exit node into the torrc file, but has anyone done that?
--
I rarely fail at getting any computer program to do what I want it to do.
But sometimes a program is so un-customizable, that even I just give up.
Re: PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
Author: Maria Sophia
Date: Sun, 08 Nov 2026 07:45
Date: Sun, 08 Nov 2026 07:45
338 lines
15788 bytes
15788 bytes
Maria Sophia wrote:
> Best is a set of nodes for profile1, another set for profile 2, etc.
> That way, it looks "normal" to the social (or throwaway email) web site.
I'm getting tired after investing a few hours fixing the problems with the
Firefox Tor browser when it comes to choosing exit nodes on the fly.
The code I hacked out below works on my Windows system, but if we want to
port it to Linux, we likely will have to port it to Python first.
The only reason it was written first in Powershell was that the initial
tests (version 1.0) used Powershell, and then it just grew from there.
Anyway, if the Firefox Tor browser is running, this will kill it and then
pop up a query for us to choose which exit nodes we want and then the
script will run the Firefox Tor browser using the selected exit nodes.
As far as I'm aware, this functionality doesn't exist on the net anywhere
but in this post as I didn't want to write it but I couldn't find it.
=== cut here for typical output ===
torset.bat
----------------------------------------
Tor exit node selector
----------------------------------------
1 for Profile 1 (two possible exit nodes)
2 for Profile 2 (one exit node)
3 for Profile 3 (one exit node)
Select profile [1,2,3] or Q to quit: 1
Setting Profile 1...
Ensuring clean state by stopping any existing Tor instances...
Tor Browser is not running. Starting Tor Browser automatically...
Waiting for Tor Browser to initialize and open ControlPort (9151)...
Tor Browser port is open.
Authentication: 250 OK
Waiting for Tor bootstrap to complete...
Tor bootstrap complete (100).
Exit configuration: 250 ExitNodes={US}
SETCONF response: 250 OK
NEWNYM response: 250 OK
New exit configuration: 250 ExitNodes=$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C
ExitNodes verification: Match
General-purpose circuits
-------------------------
Circuit: 8
Exit fingerprint: 634B891DAF74FB17C94C4AA73CB394CE6B2531F1
Profile comparison: Not in profile
Circuit: 18
Exit fingerprint: 688604204AF0C0473DFFA8CD2E186D1EEAEE6916
Profile comparison: Match
Circuit inspection complete.
Tor control session completed successfully.
torset completed successfully.
Press any key to continue . . .
=== cut here for typical output ===
:: ---------------------------------------------------------------------
:: torset.bat
:: Manually set known-good Tor exit nodes for specific web-login profiles
:: Should be ported to python so that it can be ported to Linux as needed
:: ---------------------------------------------------------------------
:: Usage notes:
:: 1. Obtain desired US Tor exit relays:
:: https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
:: 2. Enter their fingerprints in the profile definitions below.
:: 3. Run this script. It cleans up stale sessions, starts Tor, and sets nodes.
:: 4. Allow Tor a bit of time to establish new circuits.
:: 5. Verify the exit relay and exit IP before logging in.
:: ---------------------------------------------------------------------
:: v2p4 20261108 Handled stale process cleanup cleanly in native batch
:: v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
:: v2p2 20261108 Added full bootstrap completion polling on cold start
:: v2p1 20261108 Fixed $tcp variable scope in try/finally block
:: v2p0 20261108 Added automated Tor Browser startup and port polling
:: v1p9 20261108 Added ControlPort error handling and response validation
:: v1p8 20261108 Cleaned up comments and clarified explanations
:: v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
:: v1p6 20261108 Display multi-line Tor circuit status via GETINFO
:: v1p5 20261108 Request new Tor circuits after profile selection
:: v1p4 20261108 Added multi-profile exit-node selection menu
:: v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
:: v1p2 20261108 Added GETINFO status/bootstrap-phase
:: v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
:: v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
:: ---------------------------------------------------------------------
:: Summary:
:: 1. Stop any stale Tor Browser/Firefox instances for a clean start.
:: 2. Launch Tor Browser automatically if not running.
:: 3. Wait for Tor's ControlPort (9151) and 100% bootstrap completion.
:: 4. Connect to Tor's local ControlPort (9151).
:: 5. Authenticate using Tor's control_auth_cookie.
:: 6. Read the current ExitNodes configuration.
:: 7. Apply the selected profile's permitted exit fingerprints.
:: 8. Request new circuits using SIGNAL NEWNYM.
:: 9. Confirm the selected ExitNodes configuration.
:: 10. Check Tor's bootstrap status and inspect circuits.
::
:: Stop and report an error if a required operation fails.
:: This does not prove which circuit a particular website uses.
:: ---------------------------------------------------------------------
@echo off
:: Profile selection
echo ----------------------------------------
echo Tor exit node selector
echo ----------------------------------------
echo.
echo 1 for Profile 1 (two possible exit nodes)
echo 2 for Profile 2 (one exit node)
echo 3 for Profile 3 (one exit node)
echo.
choice /c 123Q /n /m "Select profile [1,2,3] or Q to quit: "
if errorlevel 4 exit /b
if errorlevel 3 goto profile3
if errorlevel 2 goto profile2
goto profile1
:profile1
set "PROFILE=Profile 1"
set "EXITNODES=$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
goto run
:profile2
set "PROFILE=Profile 2"
set "EXITNODES=$BD610AAEAE179EC259B022A178A75C70042407FB"
goto run
:profile3
set "PROFILE=Profile 3"
set "EXITNODES=$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
goto run
:run
echo.
echo Setting %PROFILE%...
:: Clean up any existing stale Tor/Firefox instances first
echo Ensuring clean state by stopping any existing Tor instances...
taskkill /f /im firefox.exe >nul 2>&1
timeout /t 2 /nobreak >nul
:: begin powershell block, later to be converted to python
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
"$ErrorActionPreference = 'Stop'; ^
$tcp = $null; ^
try { ^
$path = 'C:\app\browser\tbb\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie'; ^
$torExe = 'C:\app\browser\tbb\Tor Browser\Browser\firefox.exe'; ^
^
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { ^
Write-Host 'Tor Browser is not running. Starting Tor Browser automatically...'; ^
if (-not (Test-Path -LiteralPath $torExe)) { throw 'Tor Browser executable not found at: ' + $torExe }; ^
Start-Process -FilePath $torExe; ^
Write-Host 'Waiting for Tor Browser to initialize and open ControlPort (9151)...'; ^
$sw = [Diagnostics.Stopwatch]::StartNew(); ^
$ready = $false; ^
while ($sw.ElapsedMilliseconds -lt 45000) { ^
if (Test-Path -LiteralPath $path) { ^
try { ^
$testTcp = New-Object System.Net.Sockets.TcpClient; ^
$testTcp.Connect('127.0.0.1', 9151); ^
$testTcp.Close(); ^
$ready = $true; ^
break; ^
} catch { } ^
}; ^
Start-Sleep -Seconds 2; ^
}; ^
$sw.Stop(); ^
if (-not $ready) { throw 'Timed out waiting for Tor Browser to start and open ControlPort 9151.' }; ^
Write-Host 'Tor Browser port is open.'; ^
}; ^
^
if ([string]::IsNullOrWhiteSpace($env:EXITNODES)) { throw 'No exit nodes defined for this profile.' }; ^
$cookie = [BitConverter]::ToString([IO.File]::ReadAllBytes($path)).Replace('-', ''); ^
$tcp = New-Object System.Net.Sockets.TcpClient; ^
$tcp.ReceiveTimeout = 15000; ^
$tcp.SendTimeout = 15000; ^
$tcp.Connect('127.0.0.1', 9151); ^
$stream = $tcp.GetStream(); ^
$stream.ReadTimeout = 15000; ^
$writer = New-Object System.IO.StreamWriter($stream); ^
$reader = New-Object System.IO.StreamReader($stream); ^
$writer.NewLine = [char]13 + [char]10; ^
$writer.AutoFlush = $true; ^
^
function Read-TorReply { ^
$lines = New-Object 'System.Collections.Generic.List[string]'; ^
while ($true) { ^
$line = $reader.ReadLine(); ^
if ($null -eq $line) { throw 'Tor closed the ControlPort connection unexpectedly.' }; ^
[void]$lines.Add($line); ^
if ($line -match '^250\+') { ^
do { ^
$dataLine = $reader.ReadLine(); ^
if ($null -eq $dataLine) { throw 'Tor closed the connection during a data response.' }; ^
[void]$lines.Add($dataLine); ^
} while ($dataLine -ne '.'); ^
continue ^
}; ^
if ($line -match '^\d{3}-') { continue }; ^
break ^
}; ^
return $lines.ToArray() ^
}; ^
^
function Send-TorCommand($command) { ^
$writer.WriteLine($command); ^
$reply = @(Read-TorReply); ^
if ($reply.Count -eq 0 -or $reply[0] -notmatch '^250[ +\-]') { ^
throw ('Tor rejected command: ' + $command + ' -- ' + ($reply -join ' ')) ^
}; ^
return ,$reply ^
}; ^
^
$auth = Send-TorCommand ('AUTHENTICATE ' + $cookie); ^
Write-Host ('Authentication: ' + $auth[0]); ^
^
Write-Host 'Waiting for Tor bootstrap to complete...'; ^
$bootstrapComplete = $false; ^
$bSw = [Diagnostics.Stopwatch]::StartNew(); ^
while ($bSw.ElapsedMilliseconds -lt 60000) { ^
try { ^
$bootstrap = Send-TorCommand 'GETINFO status/bootstrap-phase'; ^
foreach ($line in $bootstrap) { ^
if ($line -match 'PROGRESS=100') { ^
$bootstrapComplete = $true; ^
break; ^
} ^
}; ^
if ($bootstrapComplete) { break }; ^
} catch { } ^
Start-Sleep -Seconds 2; ^
}; ^
$bSw.Stop(); ^
if (-not $bootstrapComplete) { throw 'Timed out waiting for Tor to finish bootstrapping.' }; ^
Write-Host 'Tor bootstrap complete (100%).'; ^
^
$config = Send-TorCommand 'GETCONF ExitNodes'; ^
Write-Host ('Exit configuration: ' + ($config -join ' ')); ^
$setconf = Send-TorCommand ('SETCONF ExitNodes=' + $env:EXITNODES); ^
Write-Host ('SETCONF response: ' + $setconf[-1]); ^
$newnym = Send-TorCommand 'SIGNAL NEWNYM'; ^
Write-Host ('NEWNYM response: ' + $newnym[-1]); ^
Start-Sleep -Seconds 3; ^
^
$config = Send-TorCommand 'GETCONF ExitNodes'; ^
Write-Host ('New exit configuration: ' + ($config -join ' ')); ^
$actualLine = $null; ^
foreach ($item in $config) { ^
if ($item -match '^250 ExitNodes=') { $actualLine = $item; break } ^
}; ^
if (-not $actualLine) { throw 'Could not verify the new ExitNodes configuration.' }; ^
^
$actualNodes = @(); ^
$actualText = $actualLine -replace '^250 ExitNodes=', ''; ^
foreach ($fp in ($actualText -split ',')) { ^
$actualNodes += $fp.Trim().TrimStart('$').ToUpperInvariant() ^
}; ^
^
$expectedNodes = @(); ^
foreach ($fp in ($env:EXITNODES -split ',')) { ^
$expectedNodes += $fp.Trim().TrimStart('$').ToUpperInvariant() ^
}; ^
if ($actualNodes.Count -ne $expectedNodes.Count) { throw 'ExitNodes verification failed: fingerprint count differs.' }; ^
foreach ($fp in $expectedNodes) { ^
if (-not ($actualNodes -contains $fp)) { throw ('ExitNodes verification failed: missing fingerprint ' + $fp) } ^
}; ^
Write-Host 'ExitNodes verification: Match'; ^
^
$allowed = @{}; ^
foreach ($fp in $expectedNodes) { ^
$allowed[$fp] = $true ^
}; ^
^
$circuitReply = Send-TorCommand 'GETINFO circuit-status'; ^
Write-Host ''; ^
Write-Host 'General-purpose circuits'; ^
Write-Host '-------------------------'; ^
$found = $false; ^
foreach ($line in $circuitReply) { ^
if ($line -notmatch '^\d+\s+BUILT\s+') { continue }; ^
if ($line -notmatch 'PURPOSE=GENERAL') { continue }; ^
$fields = $line -split '\s+'; ^
if ($fields.Count -lt 3) { continue }; ^
$hops = $fields[2] -split ','; ^
$last = ($hops[-1] -split '~')[0].TrimStart('$').ToUpperInvariant(); ^
$found = $true; ^
Write-Host ''; ^
Write-Host ('Circuit: ' + $fields[0]); ^
Write-Host ('Exit fingerprint: ' + $last); ^
if ($allowed.ContainsKey($last)) { ^
Write-Host 'Profile comparison: Match' ^
} else { ^
Write-Host 'Profile comparison: Not in profile' ^
}; ^
}; ^
if (-not $found) { ^
Write-Host 'No built general-purpose circuits found.' ^
}; ^
Write-Host ''; ^
Write-Host 'Circuit inspection complete.'; ^
Write-Host 'Tor control session completed successfully.'; ^
} catch { ^
Write-Host ''; ^
Write-Host ('Error: ' + $_.Exception.Message) -ForegroundColor Red; ^
exit 1 ^
} finally { ^
if ($tcp) { $tcp.Close() } ^
}"
:: end of powershell block
if errorlevel 1 (
echo.
echo torset did not complete successfully.
) else (
echo.
echo torset completed successfully.
)
pause
:: ---------------------------------------------------------------------
:: end of torset.bat
:: ---------------------------------------------------------------------
--
Usenet should be a discussion where everyone adds value to the topic.
Re: PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
Author: Maria Sophia
Date: Sun, 08 Nov 2026 18:49
Date: Sun, 08 Nov 2026 18:49
350 lines
14778 bytes
14778 bytes
#!/usr/bin/env python3
# ---------------------------------------------------------------------
# torset.py
# Manually set known-good Tor exit nodes for specific web-login profiles
# ---------------------------------------------------------------------
# Usage notes:
# 1. Obtain desired US Tor exit relays:
# https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
# For example:
# "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
# "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
# "$BD610AAEAE179EC259B022A178A75C70042407FB",
# "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
# 2. Enter desired fingerprints in the profile definitions, e.g.,
# Profile 1
# "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
# "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
# Profile 2
# "$BD610AAEAE179EC259B022A178A75C70042407FB",
# Profile 3
# "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
# 3. Run this script, which cleans stale sessions before starting
# Tor and allowing the user the choice of setting exit nodes
# 4. Allow Tor a bit of time to establish new circuits
# 5. Verify the exit relay and exit IP before logging in
# ---------------------------------------------------------------------
# v2p8 20261108 Reverted profile exit nodes back to original configurations
# v2p7 20261108 Converted native batch/PowerShell implementation to pure Python
# v2p6 20261108 Improved documentation block details and accuracy
# v2p5 20261108 Added new exit nodes and a profile configuration check
# v2p4 20261108 Handled stale process cleanup cleanly in native batch
# v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
# v2p2 20261108 Added full bootstrap completion polling on cold start
# v2p1 20261108 Fixed $tcp variable scope in try/finally block
# v2p0 20261108 Added automated Tor Browser startup and port polling
# v1p9 20261108 Added ControlPort error handling and response validation
# v1p8 20261108 Cleaned up comments and clarified explanations
# v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
# v1p6 20261108 Display multi-line Tor circuit status via GETINFO
# v1p5 20261108 Request new Tor circuits after profile selection
# v1p4 20261108 Added multi-profile exit-node selection menu
# v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
# v1p2 20261108 Added GETINFO status/bootstrap-phase
# v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
# v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
# ---------------------------------------------------------------------
# Summary:
# 1. Present a multi-profile selection menu allowing the user to choose
# between predefined exit-node configurations (or quit with Q).
# 2. Terminate any stale or running instances of Firefox Tor Browser
# to ensure a clean starting environment.
# 3. Launch the Firefox Tor Browser executable automatically if it is
# not currently running on the system.
# 4. Poll local TCP port 9151 and monitor for the existence of Tor's
# control authentication cookie file.
# 5. Open a local TCP socket connection to Tor's ControlPort
# (127.0.0.1:9151) once it becomes available.
# 6. Authenticate the control session securely using the binary bytes
# read from Tor's local control_auth_cookie.
# 7. Poll Tor's bootstrap status via GETINFO until the bootstrap-phase
# reports 100% completion.
# 8. Apply the user's selected profile fingerprints to Tor's configuration
# using the SETCONF ExitNodes command.
# 9. Issue a SIGNAL NEWNYM command to force Tor to discard old circuits
# and build new ones using the designated exit nodes.
# 10. Verify that the active ExitNodes configuration matches the expected
# profile fingerprints.
# 11. Query active circuits (GETINFO circuit-status), parse their exit node
# fingerprints and compare them against the profile whitelist.
# 12. Output clear verification results to the user console and pause
# before exiting, leaving the configured browser ready for secure use.
# ---------------------------------------------------------------------
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
# --- Configuration & Paths ---
COOKIE_PATH = Path(
r"C:\app\browser\tbb\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie"
)
TOR_EXE = Path(r"C:\app\browser\tbb\Tor Browser\Browser\firefox.exe")
CONTROL_PORT = 9151
# Define selectable profiles with your original exit node fingerprints
PROFILES = {
"1": {
"name": "Profile 1",
"exit_nodes": (
"$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,"
"$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
),
},
"2": {
"name": "Profile 2",
"exit_nodes": "$BD610AAEAE179EC259B022A178A75C70042407FB",
},
"3": {
"name": "Profile 3",
"exit_nodes": "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
},
}
def main():
# Step 1: Profile Selection Menu
print("----------------------------------------")
print(" Tor exit node selector ")
print("----------------------------------------")
print()
print(" 1 for Profile 1")
print(" 2 for Profile 2")
print(" 3 for Profile 3")
print(" Q to Quit")
print()
choice = input("Select profile [1,2,3] or Q to quit: ").strip().upper()
if choice == "Q" or choice not in PROFILES:
print("Exiting.")
sys.exit(0)
profile = PROFILES[choice]
print(f"\nSetting {profile['name']}...")
# Step 2: Clean up any stale or running Tor/Firefox instances
print("Ensuring clean state by stopping any existing Tor instances...")
try:
subprocess.run(
["taskkill", "/f", "/im", "firefox.exe"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception:
pass
time.sleep(2)
# Steps 3 & 4: Launch browser if needed and wait for ControlPort & cookie
if not COOKIE_PATH.is_file():
print("Tor Browser is not running. Starting Tor Browser automatically...")
if not TOR_EXE.is_file():
print(f"ERROR: Tor Browser executable not found at: {TOR_EXE}")
sys.exit(1)
subprocess.Popen([str(TOR_EXE)])
print("Waiting for Tor Browser to initialize and open ControlPort (9151)...")
start_time = time.time()
ready = False
while time.time() - start_time < 45:
if COOKIE_PATH.is_file():
try:
test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_sock.settimeout(2)
test_sock.connect(("127.0.0.1", CONTROL_PORT))
test_sock.close()
ready = True
break
except (socket.error, OSError):
pass
time.sleep(2)
if not ready:
print(
"ERROR: Timed out waiting for Tor Browser to start and open ControlPort"
" 9151."
)
sys.exit(1)
print("Tor Browser port is open.")
# Step 6: Read authentication cookie bytes
try:
cookie_bytes = COOKIE_PATH.read_bytes()
cookie_hex = cookie_bytes.hex().upper()
except Exception as e:
print(f"ERROR: Failed to read control authentication cookie: {e}")
sys.exit(1)
# Helper functions for Tor Control Protocol
def read_tor_reply(sock_file):
lines = []
while True:
line = sock_file.readline()
if not line:
raise RuntimeError("Tor closed the ControlPort connection unexpectedly.")
decoded = line.decode("utf-8", errors="ignore").rstrip("\r\n")
lines.append(decoded)
if decoded.startswith("250+"):
while True:
data_line = sock_file.readline()
if not data_line:
raise RuntimeError(
"Tor closed the connection during a data response."
)
d_decoded = data_line.decode("utf-8", errors="ignore").rstrip(
"\r\n"
)
lines.append(d_decoded)
if d_decoded == ".":
break
continue
if len(decoded) >= 4 and decoded[3] == "-":
continue
break
return lines
def send_command(sock_file, command):
sock_file.write((command + "\r\n").encode("utf-8"))
sock_file.flush()
reply = read_tor_reply(sock_file)
if not reply or not reply[0].startswith("250"):
raise RuntimeError(f"Tor rejected command: {command} -- {' '.join(reply)}")
return reply
# Step 5: Connect to ControlPort
stream = None
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(15)
s.connect(("127.0.0.1", CONTROL_PORT))
stream = s.makefile("rwb")
# Authenticate session
auth_reply = send_command(stream, f"AUTHENTICATE {cookie_hex}")
print(f"Authentication: {auth_reply[0]}")
# Step 7: Wait for Tor bootstrap completion (100%)
print("Waiting for Tor bootstrap to complete...")
bootstrap_complete = False
b_start = time.time()
while time.time() - b_start < 60:
try:
bootstrap_reply = send_command(stream, "GETINFO status/bootstrap-phase")
for line in bootstrap_reply:
if "PROGRESS=100" in line:
bootstrap_complete = True
break
if bootstrap_complete:
break
except Exception:
pass
time.sleep(2)
if not bootstrap_complete:
raise RuntimeError("Timed out waiting for Tor to finish bootstrapping.")
print("Tor bootstrap complete (100%).")
# Step 8: Apply selected profile ExitNodes via SETCONF
config_reply = send_command(stream, "GETCONF ExitNodes")
print(f"Exit configuration: {' '.join(config_reply)}")
setconf_reply = send_command(
stream, f"SETCONF ExitNodes={profile['exit_nodes']}"
)
print(f"SETCONF response: {setconf_reply[-1]}")
# Step 9: Signal NEWNYM to clear circuits and build new ones
newnym_reply = send_command(stream, "SIGNAL NEWNYM")
print(f"NEWNYM response: {newnym_reply[-1]}")
time.sleep(3)
# Step 10: Verify new ExitNodes configuration matches expected
config_reply = send_command(stream, "GETCONF ExitNodes")
print(f"New exit configuration: {' '.join(config_reply)}")
actual_line = None
for item in config_reply:
if item.startswith("250 ExitNodes="):
actual_line = item
break
if not actual_line:
raise RuntimeError("Could not verify the new ExitNodes configuration.")
actual_text = actual_line.replace("250 ExitNodes=", "")
actual_nodes = [
fp.strip().lstrip("$").upper() for fp in actual_text.split(",") if fp
]
expected_nodes = [
fp.strip().lstrip("$").upper()
for fp in profile["exit_nodes"].split(",")
if fp
]
if set(actual_nodes) != set(expected_nodes):
raise RuntimeError("ExitNodes verification failed: fingerprint mismatch.")
print("ExitNodes verification: Match")
allowed = {fp: True for fp in expected_nodes}
# Step 11: Inspect circuit-status and compare exit fingerprints
circuit_reply = send_command(stream, "GETINFO circuit-status")
print("\nGeneral-purpose circuits")
print("-------------------------")
found = False
for line in circuit_reply:
if "BUILT" not in line or "PURPOSE=GENERAL" not in line:
continue
fields = line.split()
if len(fields) < 3:
continue
circuit_id = fields[0]
hops = fields[2].split(",")
last_hop = hops[-1].split("~")[0].lstrip("$").upper()
found = True
print(f"\nCircuit: {circuit_id}")
print(f"Exit fingerprint: {last_hop}")
if last_hop in allowed:
print("Profile comparison: Match")
else:
print("Profile comparison: Not in profile")
if not found:
print("No built general-purpose circuits found.")
print("\nCircuit inspection complete.")
print("Tor control session completed successfully.")
except Exception as e:
print(f"\nError: {e}", file=sys.stderr)
sys.exit(1)
finally:
if stream:
try:
stream.close()
except Exception:
pass
if s:
try:
s.close()
except Exception:
pass
# Step 12: Output final success message and pause before exit
print("\ntorset completed successfully.")
input("Press Enter to continue . . . ")
if __name__ == "__main__":
main()
# ---------------------------------------------------------------------
# end of torset.py
# ---------------------------------------------------------------------
--
Every working example is someone paying forward a hard-learned lesson.
Re: PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
Author: Maria Sophia
Date: Mon, 09 Nov 2026 14:36
Date: Mon, 09 Nov 2026 14:36
396 lines
18359 bytes
18359 bytes
Maria Sophia wrote:
> PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
Below is portable code that should work on all the major platforms
(Linux/macOS/Windows) to choose per-profile FF Tor browser exit nodes.
I started this project five effort-hours ago assuming it would only
take a few minutes, so I used PowerShell at first, but to leverage
the effort to as many people as possible, which I am won't to do,
I expended another hour to port to Python and then to all platforms.
I tested the code below ONLY on Windows 10, so if someone can test
it on macOS and/or Linux, that would be very useful for the community.
Everything we do, is for everyone to benefit from.
That's how we're wired.
#!/usr/bin/env python3
# ---------------------------------------------------------------------
# torset.py
# Manually set known-good Tor exit nodes for specific web-login profiles
# ---------------------------------------------------------------------
# Usage notes:
# 1. Obtain a set of desired known-to-be-working US Tor exit relays:
# https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
# For example:
# "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
# "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
# "$BD610AAEAE179EC259B022A178A75C70042407FB"
# "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
# 2. Enter their fingerprints in the profile definitions, e.g.,
# Profile 1 (gmail)
# "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
# "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
# Profile 2 (protonmail)
# "$BD610AAEAE179EC259B022A178A75C70042407FB"
# Profile 3 (facebook)
# "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
# 3. Run this script, which cleans stale sessions before starting
# Tor and then provides a choice of pre-selected exit nodes
# Note: Due to Firefox Tor browser complexities, allow Tor a bit of
# time to establish new circuits and then make sure to manually
# verify the exit relay and exit IP before logging in
# ---------------------------------------------------------------------
# v2p9 20261109 Added sys.platform support for macOS and Linux paths
# v2p8 20261109 Reverted profile exit nodes back to original configurations
# v2p7 20261108 Converted native batch/PowerShell implementation to Python
# v2p6 20261108 Improved documentation in terms of technical accuracy
# v2p5 20261108 Added new exit nodes and a profile configuration check
# v2p4 20261108 Handled stale process cleanup cleanly in native batch
# v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
# v2p2 20261108 Added full bootstrap completion polling on cold start
# v2p1 20261108 Fixed $tcp variable scope in try/finally block
# v2p0 20261108 Added automated Tor Browser startup and port polling
# v1p9 20261108 Added ControlPort error handling and response validation
# v1p8 20261108 Cleaned up comments and clarified explanations
# v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
# v1p6 20261108 Display multi-line Tor circuit status via GETINFO
# v1p5 20261108 Request new Tor circuits after profile selection
# v1p4 20261108 Added multi-profile exit-node selection menu
# v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
# v1p2 20261108 Added GETINFO status/bootstrap-phase
# v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
# v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
# ---------------------------------------------------------------------
# See also...
# Forces a new working Tor exit node:
# <https://github.com/gmolop/Tor-ExitNode-changer/>
# <https://github.com/hevnsnt/IPChanger>
# <https://gist.github.com/kirelagin/9667900>
# Interacts with Tor using the Python stem library:
# <https://pypi.org/project/stem/> <https://stem.torproject.org/>
# <https://github.com/torproject/stem>
# Command-line Tor interaction and Nyx monitor:
# <https://nyx.torproject.org/> <https://github.com/torproject/nyx>
# Configures Tor using a GUI (Windows only):
# <https://github.com/abysshint/tor-control-panel/>
# ---------------------------------------------------------------------
# Summary:
# 1. Present a multi-profile selection menu allowing the user to choose
# between predefined exit-node configurations (or quit with Q).
# 2. Terminate any stale or running instances of Firefox Tor Browser
# to ensure a clean starting environment.
# 3. Launch the Firefox Tor Browser executable automatically if it is
# not currently running on the system.
# 4. Poll local TCP port 9151 and monitor for the existence of Tor's
# control authentication cookie file.
# 5. Open a local TCP socket connection to Tor's ControlPort
# (127.0.0.1:9151) once it becomes available.
# 6. Authenticate the control session securely using the binary bytes
# read from Tor's local control_auth_cookie.
# 7. Poll Tor's bootstrap status via GETINFO until the bootstrap-phase
# reports 100% completion.
# 8. Apply the user's selected profile fingerprints to Tor's configuration
# using the SETCONF ExitNodes command.
# 9. Issue a SIGNAL NEWNYM command to force Tor to discard old circuits
# and build new ones using the designated exit nodes.
# 10. Verify that the active ExitNodes configuration matches the expected
# profile fingerprints.
# 11. Query active circuits (GETINFO circuit-status), parse their exit node
# fingerprints and compare them against the profile whitelist.
# 12. Output clear verification results to the user console and pause
# before exiting, leaving the configured browser ready for secure use.
# ---------------------------------------------------------------------
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
# --- Configuration & Cross-Platform Paths ---
if sys.platform == "win32":
COOKIE_PATH = Path(
r"C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie"
)
TOR_EXE = Path(r"C:\app\browser\tor\Tor Browser\Browser\firefox.exe")
KILL_CMD = ["taskkill", "/f", "/im", "firefox.exe"]
elif sys.platform == "darwin": # macOS
TOR_EXE = Path.home() / "Applications" / "TorBrowser.app" / "Contents" / "MacOS" / "firefox"
if not TOR_EXE.is_file():
TOR_EXE = Path("/Applications/TorBrowser.app/Contents/MacOS/firefox")
COOKIE_PATH = Path.home() / "Library" / "Application Support" / "TorBrowser-Data" / "Tor" / "control_auth_cookie"
KILL_CMD = ["pkill", "-f", "torbrowser"]
else: # Linux and other Unix-likes
base_linux = Path.home() / ".local" / "share" / "torbrowser" / "tor" / "x86_64" / "tor-browser"
TOR_EXE = base_linux / "Browser" / "firefox"
COOKIE_PATH = base_linux / "Browser" / "TorBrowser" / "Data" / "Tor" / "control_auth_cookie"
KILL_CMD = ["pkill", "-f", "tor-browser"]
CONTROL_PORT = 9151
# Define selectable profiles with your original exit node fingerprints
PROFILES = {
"1": {
"name": "Profile 1",
"exit_nodes": (
"$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,"
"$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
),
},
"2": {
"name": "Profile 2",
"exit_nodes": "$BD610AAEAE179EC259B022A178A75C70042407FB",
},
"3": {
"name": "Profile 3",
"exit_nodes": "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
},
}
def main():
# Step 1: Profile Selection Menu
print("----------------------------------------")
print(" Tor exit node selector ")
print("----------------------------------------")
print()
print(" 1 for Profile 1")
print(" 2 for Profile 2")
print(" 3 for Profile 3")
print(" Q to Quit")
print()
choice = input("Select profile [1,2,3] or Q to quit: ").strip().upper()
if choice == "Q" or choice not in PROFILES:
print("Exiting.")
sys.exit(0)
profile = PROFILES[choice]
print(f"\nSetting {profile['name']}...")
# Step 2: Clean up any stale or running Tor/Firefox instances
print("Ensuring clean state by stopping any existing Tor instances...")
try:
subprocess.run(
KILL_CMD,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception:
pass
time.sleep(2)
# Steps 3 & 4: Launch browser if needed and wait for ControlPort & cookie
if not COOKIE_PATH.is_file():
print("Tor Browser is not running. Starting Tor Browser automatically...")
if not TOR_EXE.is_file():
print(f"ERROR: Tor Browser executable not found at: {TOR_EXE}")
sys.exit(1)
subprocess.Popen([str(TOR_EXE)])
print("Waiting for Tor Browser to initialize and open ControlPort (9151)...")
start_time = time.time()
ready = False
while time.time() - start_time < 45:
if COOKIE_PATH.is_file():
try:
test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_sock.settimeout(2)
test_sock.connect(("127.0.0.1", CONTROL_PORT))
test_sock.close()
ready = True
break
except (socket.error, OSError):
pass
time.sleep(2)
if not ready:
print(
"ERROR: Timed out waiting for Tor Browser to start and open ControlPort"
" 9151."
)
sys.exit(1)
print("Tor Browser port is open.")
# Step 6: Read authentication cookie bytes
try:
cookie_bytes = COOKIE_PATH.read_bytes()
cookie_hex = cookie_bytes.hex().upper()
except Exception as e:
print(f"ERROR: Failed to read control authentication cookie: {e}")
sys.exit(1)
# Helper functions for Tor Control Protocol
def read_tor_reply(sock_file):
lines = []
while True:
line = sock_file.readline()
if not line:
raise RuntimeError("Tor closed the ControlPort connection unexpectedly.")
decoded = line.decode("utf-8", errors="ignore").rstrip("\r\n")
lines.append(decoded)
if decoded.startswith("250+"):
while True:
data_line = sock_file.readline()
if not data_line:
raise RuntimeError(
"Tor closed the connection during a data response."
)
d_decoded = data_line.decode("utf-8", errors="ignore").rstrip(
"\r\n"
)
lines.append(d_decoded)
if d_decoded == ".":
break
continue
if len(decoded) >= 4 and decoded[3] == "-":
continue
break
return lines
def send_command(sock_file, command):
sock_file.write((command + "\r\n").encode("utf-8"))
sock_file.flush()
reply = read_tor_reply(sock_file)
if not reply or not reply[0].startswith("250"):
raise RuntimeError(f"Tor rejected command: {command} -- {' '.join(reply)}")
return reply
# Step 5: Connect to ControlPort
stream = None
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(15)
s.connect(("127.0.0.1", CONTROL_PORT))
stream = s.makefile("rwb")
# Authenticate session
auth_reply = send_command(stream, f"AUTHENTICATE {cookie_hex}")
print(f"Authentication: {auth_reply[0]}")
# Step 7: Wait for Tor bootstrap completion (100%)
print("Waiting for Tor bootstrap to complete...")
bootstrap_complete = False
b_start = time.time()
while time.time() - b_start < 60:
try:
bootstrap_reply = send_command(stream, "GETINFO status/bootstrap-phase")
for line in bootstrap_reply:
if "PROGRESS=100" in line:
bootstrap_complete = True
break
if bootstrap_complete:
break
except Exception:
pass
time.sleep(2)
if not bootstrap_complete:
raise RuntimeError("Timed out waiting for Tor to finish bootstrapping.")
print("Tor bootstrap complete (100%).")
# Step 8: Apply selected profile ExitNodes via SETCONF
config_reply = send_command(stream, "GETCONF ExitNodes")
print(f"Exit configuration: {' '.join(config_reply)}")
setconf_reply = send_command(
stream, f"SETCONF ExitNodes={profile['exit_nodes']}"
)
print(f"SETCONF response: {setconf_reply[-1]}")
# Step 9: Signal NEWNYM to clear circuits and build new ones
newnym_reply = send_command(stream, "SIGNAL NEWNYM")
print(f"NEWNYM response: {newnym_reply[-1]}")
time.sleep(3)
# Step 10: Verify new ExitNodes configuration matches expected
config_reply = send_command(stream, "GETCONF ExitNodes")
print(f"New exit configuration: {' '.join(config_reply)}")
actual_line = None
for item in config_reply:
if item.startswith("250 ExitNodes="):
actual_line = item
break
if not actual_line:
raise RuntimeError("Could not verify the new ExitNodes configuration.")
actual_text = actual_line.replace("250 ExitNodes=", "")
actual_nodes = [
fp.strip().lstrip("$").upper() for fp in actual_text.split(",") if fp
]
expected_nodes = [
fp.strip().lstrip("$").upper()
for fp in profile["exit_nodes"].split(",")
if fp
]
if set(actual_nodes) != set(expected_nodes):
raise RuntimeError("ExitNodes verification failed: fingerprint mismatch.")
print("ExitNodes verification: Match")
allowed = {fp: True for fp in expected_nodes}
# Step 11: Inspect circuit-status and compare exit fingerprints
circuit_reply = send_command(stream, "GETINFO circuit-status")
print("\nGeneral-purpose circuits")
print("-------------------------")
found = False
for line in circuit_reply:
if "BUILT" not in line or "PURPOSE=GENERAL" not in line:
continue
fields = line.split()
if len(fields) < 3:
continue
circuit_id = fields[0]
hops = fields[2].split(",")
last_hop = hops[-1].split("~")[0].lstrip("$").upper()
found = True
print(f"\nCircuit: {circuit_id}")
print(f"Exit fingerprint: {last_hop}")
if last_hop in allowed:
print("Profile comparison: Match")
else:
print("Profile comparison: Not in profile")
if not found:
print("No built general-purpose circuits found.")
print("\nCircuit inspection complete.")
print("Tor control session completed successfully.")
except Exception as e:
print(f"\nError: {e}", file=sys.stderr)
sys.exit(1)
finally:
if stream:
try:
stream.close()
except Exception:
pass
if s:
try:
s.close()
except Exception:
pass
# Step 12: Output final success message and pause before exit
print("\ntorset completed successfully.")
input("Press Enter to continue . . . ")
if __name__ == "__main__":
main()
# ---------------------------------------------------------------------
# end of torset.py
# ---------------------------------------------------------------------
--
On Usenet, a good suggestion can make everyone's solution a little better.
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads