torblock 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
torblock-1.0.1/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org>
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: torblock
3
+ Version: 1.0.1
4
+ Summary: Tor exit node blocking code generator.
5
+ Author: V. Alex Brennen
6
+ Author-email: V. Alex Brennen <vab@cryptnet.net>
7
+ License-Expression: Unlicense
8
+ License-File: LICENSE
9
+ Requires-Dist: argparse>=1.4.0
10
+ Requires-Dist: ipaddress>=1.0.23
11
+ Requires-Dist: requests>=2.34.2
12
+ Requires-Python: >=3.14
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Tor Network Exit Node Blocking Automation
16
+ <!-- --8<-- [start:short] -->
17
+ *torblock* is a python program that will attempt to assist administrators in blocking all known Tor exit nodes. It downloads the current list of Tor exit nodes from the Tor Project website [exit node list](https://check.torproject.org/exit-addresses). It produces a raw list of IP addresses or commands that can be used with various web servers or firewalls.
18
+ <!-- --8<-- [end:short] -->
19
+
20
+ ## Quickstart
21
+ <!-- --8<-- [start:quickstart] -->
22
+
23
+ Run `torblock` one time with `uvx` or `pipx` (without installing it):
24
+
25
+ ```uvx torblock -h```
26
+
27
+ ```pipx run torblock -h```
28
+
29
+ Install the package with `uv` or `pipx` (if desired):
30
+
31
+ ```uv tool install torblock```
32
+
33
+ ```pipx install torblock```
34
+
35
+ Run `torblock` to produce commands to block exit nodes:
36
+
37
+ For example, at the OS firewall level:
38
+ ```torblock -u /tmp/torblock-ufw-commands.txt```
39
+
40
+ For example, at the webserver level:
41
+ ```torblock -n /tmp/torblock-nginx-commands.txt```
42
+
43
+ Review the commands produced by `torblock` and then either add them to your configuration or run them on the command line.
44
+ <!-- --8<-- [end:quickstart] -->
45
+
46
+ ## Documentation
47
+
48
+ *torblock* attempts to assist administrators in blocking all traffic and access attempts from exit nodes in the Tor network. Tor is an onion mix network that allows users to hide their identities. Exit nodes are Tor nodes that are configured to provide gateway service between the Tor network and the public internet. This functionality is often used for nefarious purposes such as unauthorized access or data exfiltration. This program attempts to assist administrators in blocking exit node traffic in order to better secure their networks, systems, and services.
49
+
50
+ The Tor Project provides an up-to-date list of the IP addresses of advertised exit nodes via a REST URL. This program downloads the list of exit nodes. It then performs deduplication, validity checking, and sanity checking. The program then transforms the list of exit IP addresses into either a raw list of IP addresses or a series of commands for various web servers, firewalls, or system configuration files. The IPs or commands may be written either to a text file or to *stdout*. The commands produced can then be either run from the command line or placed in server configuration files. For security reasons, this version of *torblock* does not attempt to modify the configurations of server software, firewalls, or system configurations. That functionality may be added as an option in a future version.
51
+
52
+ > [!NOTE]
53
+ > The Tor Project currently does not support IPv6 exit nodes due to concerns that doing so would weaken anonymity protection. Therefore, torblock currently does not support IPv6 and only processes dotted-quad notation IPv4 exit node addresses.
54
+
55
+ Systems and software currently supported by *torblock* can be seen in the program help text:
56
+
57
+ ```text
58
+ usage: torblock [-h] [-q] [-a | -a22 | -i | -n | -r | -u | -w] [filename]
59
+
60
+ positional arguments:
61
+ filename Optional output filename.
62
+
63
+ options:
64
+ -h, --help show this help message and exit
65
+ -q, --quiet suppress all stdout output except block commands/node
66
+ listing
67
+ -a, --apache print notes in Apache 2.4+ blocking format
68
+ -a22, --apache22 print notes in Apache 2.2 blocking format
69
+ -i, --iptables print commands to block nodes using iptables
70
+ -n, --nginx print nodes in nginx blocking format
71
+ -r, --raw print nodes as raw ipv4s w/o subnets (default)
72
+ -u, --ufw print commands to block nodes using Ubuntu's ufw firewall
73
+ -w, --hostsdeny nodes in hosts.deny blocking format
74
+ ```
75
+
76
+ Support for additional systems, software, and data formats (such as JSON) will be added in future versions. Differential configurations are currently being worked on that will allow only new exit nodes to be added and allow old, no-longer-active nodes to be removed. Future versions of *torblock* will also expose functions and data structures to allow you to easily use it directly in your own programs and workflows.
77
+
78
+ This version of the program was designed to be run from the command line. However, at its current level of functionality, it could be added to DevOps workflows, integrated into business logic systems, or built into a workflow where it is run by cron or another scheduling system.
79
+
80
+ Feature requests, bug reports, and security advisories may be submitted through the project's [**github page**](https://github.com/vab/torblock).
81
+
82
+ > [!NOTE]
83
+ > Please keep in mind that the Tor Project is a nonprofit organization. Do not place excessive load on their website through excessively frequent querying with `torblock`. The exit nodes of the Tor network are stable and change relatively infrequently.
84
+
85
+ *torblock* was designed to completely block Tor nodes for cybersecurity purposes. However, the program can also be used to require additional security screening, segregation, quarantining, or monitoring of traffic and requests originating from Tor exit nodes. For example, raw IP address output could be used to require CAPTCHA solving, rate limiting, or redirection to a dedicated server or endpoint. Likewise, the program could also be used to whitelist Tor exit nodes. For example, raw IP address output could be used to allow users accessing sites and services from Tor exit nodes to bypass CAPTCHA solving, source-IP-based request rate limiting, or to grant longer request timeouts due to the latency introduced by the Tor network's onion routing protocol and exit node bandwidth limitations.
86
+
87
+ ## Project Links
88
+
89
+ - [**Github**](https://github.com/vab/torblock)
90
+ - [**PyPI**](https://pypi.org/project/torblock/)
91
+ - [**Additional Documentation**](https://github.com/vab/torblock/docs/README.md)
92
+ - [AWS Notes](https://github.com/vab/torblock/docs/aws.md)
93
+
94
+ ## Credits
95
+ <!-- --8<-- [start:credits] -->
96
+ *torblock* is maintained by [V. Alex Brennen](https://github.com/vab/) and released under the [The Unlicense](https://github.com/vab/torblock/blob/master/LICENSE).
97
+ <!-- --8<-- [end:credits] -->
@@ -0,0 +1,83 @@
1
+ # Tor Network Exit Node Blocking Automation
2
+ <!-- --8<-- [start:short] -->
3
+ *torblock* is a python program that will attempt to assist administrators in blocking all known Tor exit nodes. It downloads the current list of Tor exit nodes from the Tor Project website [exit node list](https://check.torproject.org/exit-addresses). It produces a raw list of IP addresses or commands that can be used with various web servers or firewalls.
4
+ <!-- --8<-- [end:short] -->
5
+
6
+ ## Quickstart
7
+ <!-- --8<-- [start:quickstart] -->
8
+
9
+ Run `torblock` one time with `uvx` or `pipx` (without installing it):
10
+
11
+ ```uvx torblock -h```
12
+
13
+ ```pipx run torblock -h```
14
+
15
+ Install the package with `uv` or `pipx` (if desired):
16
+
17
+ ```uv tool install torblock```
18
+
19
+ ```pipx install torblock```
20
+
21
+ Run `torblock` to produce commands to block exit nodes:
22
+
23
+ For example, at the OS firewall level:
24
+ ```torblock -u /tmp/torblock-ufw-commands.txt```
25
+
26
+ For example, at the webserver level:
27
+ ```torblock -n /tmp/torblock-nginx-commands.txt```
28
+
29
+ Review the commands produced by `torblock` and then either add them to your configuration or run them on the command line.
30
+ <!-- --8<-- [end:quickstart] -->
31
+
32
+ ## Documentation
33
+
34
+ *torblock* attempts to assist administrators in blocking all traffic and access attempts from exit nodes in the Tor network. Tor is an onion mix network that allows users to hide their identities. Exit nodes are Tor nodes that are configured to provide gateway service between the Tor network and the public internet. This functionality is often used for nefarious purposes such as unauthorized access or data exfiltration. This program attempts to assist administrators in blocking exit node traffic in order to better secure their networks, systems, and services.
35
+
36
+ The Tor Project provides an up-to-date list of the IP addresses of advertised exit nodes via a REST URL. This program downloads the list of exit nodes. It then performs deduplication, validity checking, and sanity checking. The program then transforms the list of exit IP addresses into either a raw list of IP addresses or a series of commands for various web servers, firewalls, or system configuration files. The IPs or commands may be written either to a text file or to *stdout*. The commands produced can then be either run from the command line or placed in server configuration files. For security reasons, this version of *torblock* does not attempt to modify the configurations of server software, firewalls, or system configurations. That functionality may be added as an option in a future version.
37
+
38
+ > [!NOTE]
39
+ > The Tor Project currently does not support IPv6 exit nodes due to concerns that doing so would weaken anonymity protection. Therefore, torblock currently does not support IPv6 and only processes dotted-quad notation IPv4 exit node addresses.
40
+
41
+ Systems and software currently supported by *torblock* can be seen in the program help text:
42
+
43
+ ```text
44
+ usage: torblock [-h] [-q] [-a | -a22 | -i | -n | -r | -u | -w] [filename]
45
+
46
+ positional arguments:
47
+ filename Optional output filename.
48
+
49
+ options:
50
+ -h, --help show this help message and exit
51
+ -q, --quiet suppress all stdout output except block commands/node
52
+ listing
53
+ -a, --apache print notes in Apache 2.4+ blocking format
54
+ -a22, --apache22 print notes in Apache 2.2 blocking format
55
+ -i, --iptables print commands to block nodes using iptables
56
+ -n, --nginx print nodes in nginx blocking format
57
+ -r, --raw print nodes as raw ipv4s w/o subnets (default)
58
+ -u, --ufw print commands to block nodes using Ubuntu's ufw firewall
59
+ -w, --hostsdeny nodes in hosts.deny blocking format
60
+ ```
61
+
62
+ Support for additional systems, software, and data formats (such as JSON) will be added in future versions. Differential configurations are currently being worked on that will allow only new exit nodes to be added and allow old, no-longer-active nodes to be removed. Future versions of *torblock* will also expose functions and data structures to allow you to easily use it directly in your own programs and workflows.
63
+
64
+ This version of the program was designed to be run from the command line. However, at its current level of functionality, it could be added to DevOps workflows, integrated into business logic systems, or built into a workflow where it is run by cron or another scheduling system.
65
+
66
+ Feature requests, bug reports, and security advisories may be submitted through the project's [**github page**](https://github.com/vab/torblock).
67
+
68
+ > [!NOTE]
69
+ > Please keep in mind that the Tor Project is a nonprofit organization. Do not place excessive load on their website through excessively frequent querying with `torblock`. The exit nodes of the Tor network are stable and change relatively infrequently.
70
+
71
+ *torblock* was designed to completely block Tor nodes for cybersecurity purposes. However, the program can also be used to require additional security screening, segregation, quarantining, or monitoring of traffic and requests originating from Tor exit nodes. For example, raw IP address output could be used to require CAPTCHA solving, rate limiting, or redirection to a dedicated server or endpoint. Likewise, the program could also be used to whitelist Tor exit nodes. For example, raw IP address output could be used to allow users accessing sites and services from Tor exit nodes to bypass CAPTCHA solving, source-IP-based request rate limiting, or to grant longer request timeouts due to the latency introduced by the Tor network's onion routing protocol and exit node bandwidth limitations.
72
+
73
+ ## Project Links
74
+
75
+ - [**Github**](https://github.com/vab/torblock)
76
+ - [**PyPI**](https://pypi.org/project/torblock/)
77
+ - [**Additional Documentation**](https://github.com/vab/torblock/docs/README.md)
78
+ - [AWS Notes](https://github.com/vab/torblock/docs/aws.md)
79
+
80
+ ## Credits
81
+ <!-- --8<-- [start:credits] -->
82
+ *torblock* is maintained by [V. Alex Brennen](https://github.com/vab/) and released under the [The Unlicense](https://github.com/vab/torblock/blob/master/LICENSE).
83
+ <!-- --8<-- [end:credits] -->
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "torblock"
3
+ version = "1.0.1"
4
+ description = "Tor exit node blocking code generator."
5
+ readme = "README.md"
6
+ license = "Unlicense"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.14"
9
+ dependencies = [
10
+ "argparse>=1.4.0",
11
+ "ipaddress>=1.0.23",
12
+ "requests>=2.34.2",
13
+ ]
14
+
15
+ [[project.authors]]
16
+ name = "V. Alex Brennen"
17
+ email = "vab@cryptnet.net"
18
+
19
+ [project.scripts]
20
+ torblock = "torblock.cli:main"
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.12.21,<=0.13.10"]
24
+ build-backend = "uv_build"
25
+
26
+ [dependency-groups]
27
+ dev = [
28
+ "pytest>=9.2.0",
29
+ "ruff>=0.17.6",
30
+ "ty>=0.0.115",
31
+ "types-requests>=2.33.0.20261030",
32
+ ]
33
+
34
+ [tool.uv.build-backend]
35
+ source-include = ["tests/**"]
36
+
37
+ [tool.setuptools.package-data]
38
+ torblock = ["py.typed"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ pythonpath = ["src"]
43
+
44
+ [tool.ruff.lint]
45
+ select = [
46
+ "E",
47
+ "F",
48
+ "I",
49
+ "UP",
50
+ "B",
51
+ ]
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "torblock"
3
+ version = "1.0.1"
4
+ description = "Tor exit node blocking code generator."
5
+ readme = "README.md"
6
+ license = "Unlicense"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "V. Alex Brennen", email = "vab@cryptnet.net" }
10
+ ]
11
+ requires-python = ">=3.14"
12
+ dependencies = [
13
+ "argparse>=1.4.0",
14
+ "ipaddress>=1.0.23",
15
+ "requests>=2.34.2",
16
+ ]
17
+
18
+ [project.scripts]
19
+ torblock = "torblock.cli:main"
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.12.21,<=0.13.10"]
23
+ build-backend = "uv_build"
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "pytest>=9.2.0",
28
+ "ruff>=0.17.6",
29
+ "ty>=0.0.115",
30
+ "types-requests>=2.33.0.20261030",
31
+ ]
32
+
33
+ [tool.uv.build-backend]
34
+ source-include = ["tests/**"]
35
+
36
+ [tool.setuptools.package-data]
37
+ torblock = ["py.typed"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
41
+ pythonpath = ["src"]
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E", "F", "I", "UP", "B"]
File without changes
@@ -0,0 +1,408 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # Generate Code to Block Tor Exit Nodes
4
+ # Author: V. Alex Brennen <vab@cryptnet.net>
5
+ # License: This script is public domain
6
+
7
+ # Description: This script attempts to generate code to block all known tor
8
+ # exit nodes (as reported by the Tor Project's website). It
9
+ # provides code for various firewalls, web servers, and the
10
+ # hostsdeny file. It can also provide a raw IP4 node list.
11
+
12
+ import argparse
13
+ import ipaddress
14
+ import re
15
+ import sys
16
+ from contextlib import nullcontext
17
+ from typing import TextIO
18
+
19
+ import requests
20
+ from requests.adapters import HTTPAdapter
21
+ from requests.exceptions import (
22
+ ConnectionError,
23
+ HTTPError,
24
+ SSLError,
25
+ Timeout,
26
+ TooManyRedirects,
27
+ )
28
+ from urllib3.util.retry import Retry
29
+
30
+
31
+ # Parse program cli arguments.
32
+ def parse_cli() -> argparse.ArgumentParser:
33
+ parser = argparse.ArgumentParser()
34
+
35
+ parser.prog = "torblock"
36
+ parser.description = "Tor network exit node blocking automation."
37
+
38
+ # Optional positional output filename
39
+ parser.add_argument(
40
+ "filename",
41
+ nargs="?",
42
+ default=None,
43
+ help="optional output filename",
44
+ )
45
+ # General options
46
+ parser.add_argument(
47
+ "-q",
48
+ "--quiet",
49
+ dest="quiet",
50
+ action="store_true",
51
+ help="suppress all stdout output except block commands/node listing",
52
+ )
53
+ # A group for formats
54
+ group = parser.add_mutually_exclusive_group()
55
+ group.add_argument(
56
+ "-a",
57
+ "--apache",
58
+ dest="fmt",
59
+ action="store_const",
60
+ const="apache",
61
+ help="print notes in Apache 2.4+ blocking formats",
62
+ )
63
+ group.add_argument(
64
+ "-a22",
65
+ "--apache22",
66
+ dest="fmt",
67
+ action="store_const",
68
+ const="apache22",
69
+ help="print notes in Apache 2.2 blocking format",
70
+ )
71
+ group.add_argument(
72
+ "-i",
73
+ "--iptables",
74
+ dest="fmt",
75
+ action="store_const",
76
+ const="iptables",
77
+ help="print commands to block nodes using iptables",
78
+ )
79
+ group.add_argument(
80
+ "-n",
81
+ "--nginx",
82
+ dest="fmt",
83
+ action="store_const",
84
+ const="nginx",
85
+ help="print nodes in nginx blocking format",
86
+ )
87
+ group.add_argument(
88
+ "-r",
89
+ "--raw",
90
+ dest="fmt",
91
+ action="store_const",
92
+ const="raw",
93
+ help="print nodes as raw ipv4s w/o subnets (default)",
94
+ )
95
+ group.add_argument(
96
+ "-u",
97
+ "--ufw",
98
+ dest="fmt",
99
+ action="store_const",
100
+ const="ufw",
101
+ help="print commands to block nodes using Ubuntu's ufw firewall",
102
+ )
103
+ group.add_argument(
104
+ "-w",
105
+ "--hostsdeny",
106
+ dest="fmt",
107
+ action="store_const",
108
+ const="hostsdeny",
109
+ help="nodes in hosts.deny blocking format",
110
+ )
111
+ # Default to raw format if output if no format was selected.
112
+ group.set_defaults(fmt="raw")
113
+
114
+ return parser
115
+
116
+
117
+ ## Retrieve the exit node list from the Tor project's website
118
+
119
+
120
+ # Create a session context for the web request
121
+ def create_session() -> requests.Session:
122
+ """Create a session with retry logic for transient errors."""
123
+ retry_strategy = Retry(
124
+ total=3,
125
+ backoff_factor=3, # 3s between retries
126
+ status_forcelist=[429, 500, 502, 503, 504],
127
+ allowed_methods=["GET"],
128
+ )
129
+ adapter = HTTPAdapter(max_retries=retry_strategy)
130
+ session = requests.Session()
131
+ session.mount("https://", adapter)
132
+ session.mount("http://", adapter)
133
+ return session
134
+
135
+
136
+ # Download the nodelist with an https request
137
+ def retrieve_nodelist(url: str) -> requests.Response | None:
138
+ response = None
139
+ timeout = 60
140
+
141
+ session = create_session()
142
+
143
+ try:
144
+ response = session.get(url, timeout=timeout)
145
+ response.raise_for_status()
146
+ return response
147
+ except SSLError as e:
148
+ print(
149
+ f"SSL error for {url}: {e}.",
150
+ file=sys.stderr,
151
+ )
152
+ print(
153
+ "Check that the server certificate is valid and your \
154
+ trusted CA bundle is current.",
155
+ file=sys.stderr,
156
+ )
157
+ return None
158
+ except ConnectionError as e:
159
+ print(
160
+ f"Connection failed for {url}: {e}",
161
+ file=sys.stderr,
162
+ )
163
+ return None
164
+ except Timeout:
165
+ print(
166
+ f"Request to {url} timed out after {timeout}",
167
+ file=sys.stderr,
168
+ )
169
+ return None
170
+ except HTTPError as e:
171
+ if e.response is not None:
172
+ status = e.response.status_code
173
+ if 400 <= status < 500:
174
+ print(
175
+ f"Client error {status} for {url}: {e.response.text[:200]}",
176
+ file=sys.stderr,
177
+ )
178
+ else:
179
+ print(
180
+ f"Server error {status} for {url} (after retries): \
181
+ {e.response.text[:200]}",
182
+ file=sys.stderr,
183
+ )
184
+ return None
185
+ except TooManyRedirects:
186
+ print(
187
+ f"Too many redirects for {url}",
188
+ file=sys.stderr,
189
+ )
190
+ return None
191
+ # General exception catch all
192
+ except Exception as e: # catch-all safety net
193
+ print(f"Unexpected error for {url}: {e}", file=sys.stderr)
194
+ return None
195
+
196
+ return response
197
+
198
+
199
+ # Parse the response into an IPv4 address list
200
+ def parse_response(response: requests.Response) -> set[str]:
201
+ node_list: list[str] = []
202
+ unique_nodes: set[str] = set()
203
+
204
+ for line in response.iter_lines():
205
+ # Decoding is done with UTF-8 because only node ip addresses are
206
+ # expected to be ASCII.
207
+ decoded_line = line.decode("UTF-8").strip()
208
+ if "ExitAddress" in decoded_line:
209
+ ip = decoded_line.split(" ", 3)
210
+ # Check for IPv4. Tor currently does not support IPv6 by
211
+ # policy for security reasons. Tor provides the addresses
212
+ # in dotted quad format. So, this regex is used as additional
213
+ # security over just the ipaddress python module validation.
214
+ if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip[1]):
215
+ add_uniquenode(ip[1], node_list, unique_nodes)
216
+ return unique_nodes
217
+
218
+
219
+ # This function adds a node IP to a string list data structure and uses a set
220
+ # to make sure it is not a duplicate. The node list returned by the tor
221
+ # project website is not guaranteed to not contain duplicate node ip listings.
222
+ # A set is used here to avoid the O(N) cost of checking "if item in list". The
223
+ # list and set are appended to here because it is more efficient than creating
224
+ # the list and then converting it to a set.
225
+ def add_uniquenode(node: str, node_list: list[str], unique_nodes: set):
226
+ if node not in unique_nodes:
227
+ node_list.append(node)
228
+ unique_nodes.add(node)
229
+
230
+
231
+ ## Validate node IPv4 addresses as public addressable
232
+
233
+
234
+ # Convert the node address to an ipaddress module IPv4Address object for
235
+ # validation processing
236
+ def ipv4_addr(ipaddr: str) -> bool:
237
+ try:
238
+ ipaddress.IPv4Address(ipaddr)
239
+ return True
240
+ except ValueError:
241
+ return False
242
+
243
+
244
+ # Perform the final validation with the ipaddress module
245
+ #
246
+ # This function makes sure we do not cause system problems by banning
247
+ # addresses that are loopback, special/reserved, or are private if the website
248
+ # returns an invalid exit node addresses.
249
+ def public_ipaddr(ipaddr: str) -> bool:
250
+ try:
251
+ ip = ipaddress.IPv4Address(ipaddr)
252
+ except ValueError:
253
+ return False
254
+
255
+ if ip.is_loopback:
256
+ return False
257
+ if ip.is_private:
258
+ return False
259
+ if ip.is_multicast:
260
+ return False
261
+ if ip.is_link_local:
262
+ return False
263
+ if ip.is_reserved:
264
+ return False
265
+ if ip.is_unspecified:
266
+ return False
267
+ return bool(ip.is_global)
268
+
269
+
270
+ ## The blocking/output functions
271
+ #
272
+ # This code was pulled out into individual functions over an inline format
273
+ # to allow a future version of this program to perform actual blocking. This
274
+ # can be done by running firewall programs such as iptables or ufw. It can
275
+ # also be done by modify webserver configuration files and reloading them.
276
+
277
+
278
+ # Generate configuration statements for Apache web servers >=2.4
279
+ def blockapache(ip: str, file_handle: TextIO):
280
+ file_handle.write(f"\tRequire not ip {ip}/32\n")
281
+
282
+
283
+ # Generate configuration statements for Apache web servers <=2.2
284
+ # The /32 subnet mask is optional. It is added here to make it explicit that
285
+ # we mean to drop a single host.
286
+ def blockapache22(ip: str, file_handle: TextIO):
287
+ file_handle.write(f"\tdeny from {ip}/32\n")
288
+
289
+
290
+ # Generate commands for the iptables firewall
291
+ # The /32 subnet mask is optional. It is added here to make it explicit that
292
+ # we mean to drop a single host.
293
+ def blockiptables(ip: str, file_handle: TextIO):
294
+ file_handle.write(f"iptables -A INPUT -s {ip}/32 -j DROP\n")
295
+
296
+
297
+ # Generate configuration statements for nginx web servers
298
+ def blocknginx(ip: str, file_handle: TextIO):
299
+ file_handle.write(f"deny {ip};\n")
300
+
301
+
302
+ # Generate commands for the Ubuntu ufw firewall
303
+ # The /32 subnet mask is optional. It is added here to make it explicit that
304
+ # we mean to drop a single host.
305
+ def blockufw(ip: str, file_handle: TextIO):
306
+ file_handle.write(f"ufw deny from {ip}/32\n")
307
+
308
+
309
+ # Generate configuration statements for host.deny files
310
+ def hostsdeny(ip: str, file_handle: TextIO):
311
+ file_handle.write(f"ALL : {ip}\n")
312
+
313
+
314
+ # Generate a raw ipv4 address file w/o subnets
315
+ def ipfile(ip: str, file_handle: TextIO):
316
+ file_handle.write(f"{ip}\n")
317
+
318
+
319
+ # The main blocking function
320
+ def blocknode(args: argparse.Namespace, file_handle: TextIO, ip: str):
321
+ if not (ipv4_addr(ip) and public_ipaddr(ip)):
322
+ return
323
+
324
+ match args.fmt:
325
+ case "apache":
326
+ # Write to file in apache format
327
+ blockapache(ip, file_handle)
328
+ case "apache22":
329
+ # Write to file in deprecated apache v2.2 format
330
+ blockapache22(ip, file_handle)
331
+ case "iptables":
332
+ blockiptables(ip, file_handle)
333
+ case "nginx":
334
+ # Write to file in nginx information
335
+ blocknginx(ip, file_handle)
336
+ case "hostsdeny":
337
+ # Write to file in hosts.deny format
338
+ hostsdeny(ip, file_handle)
339
+ case "raw":
340
+ # Write ips to file line delimited with no formatting
341
+ ipfile(ip, file_handle)
342
+ case "ufw":
343
+ # Write to file in ufw format
344
+ blockufw(ip, file_handle)
345
+
346
+
347
+ ## The main loop
348
+
349
+
350
+ # The current node list is downloaded from the Tor project's website. A stream
351
+ # is opened to output the results. The node addresses are extracted from the
352
+ # response with a regex, basic sanity checking is done, and node addresses are
353
+ # passed to the blocknode() function.
354
+ def main(argv: list[str] | None = None) -> int:
355
+ parser = parse_cli()
356
+ args = parser.parse_args()
357
+
358
+ if not args.quiet:
359
+ print("Preparing data to block all tor exit nodes.")
360
+
361
+ print("Retrieving list of nodes from Tor project website.")
362
+
363
+ exiturl = "https://check.torproject.org/exit-addresses"
364
+
365
+ response = retrieve_nodelist(exiturl)
366
+ if response is None:
367
+ print("Failed to download node list.")
368
+ return 1
369
+
370
+ if not args.quiet:
371
+ print("Node list successfully downloaded.")
372
+
373
+ # If we have a valid response, prepare to either write to a file or stdout
374
+ try:
375
+ stream_manager = (
376
+ nullcontext(sys.stdout)
377
+ if args.filename is None or args.filename == "-"
378
+ else open(args.filename, mode="w", encoding="ascii")
379
+ )
380
+ except UnicodeEncodeError as e:
381
+ print(
382
+ f"Encoding Error: Cannot write non-ASCII character. ({e})",
383
+ file=sys.stderr,
384
+ )
385
+ return 1
386
+ except (OSError, PermissionError) as e:
387
+ print(
388
+ f"File Error: Unable to write to '{args.filename}'. ({e})",
389
+ file=sys.stderr,
390
+ )
391
+ return 1
392
+
393
+ unique_nodes = parse_response(response)
394
+
395
+ with stream_manager as output_stream:
396
+ for node in unique_nodes:
397
+ blocknode(args, output_stream, node)
398
+
399
+ if not args.quiet:
400
+ print(f"Processed {len(unique_nodes)} nodes.")
401
+ print("Done.")
402
+
403
+ return 0
404
+
405
+
406
+ # Program entry point
407
+ if __name__ == "__main__":
408
+ main()
File without changes
@@ -0,0 +1,16 @@
1
+ ExitNode 64D74AAA74F30DC2CFB36343CE5D4451B9A4DBA8
2
+ Published 2026-12-02 11:01:53
3
+ LastStatus 2026-12-02 16:00:00
4
+ ExitAddress 171.25.193.25 2026-12-02 16:11:37
5
+ ExitNode 0DC16FEAA5A5E27A974009CBF7748BB6FAAE6DE1
6
+ Published 2026-12-02 02:29:07
7
+ LastStatus 2026-12-02 16:00:00
8
+ ExitAddress 80.67.167.81 2026-12-02 16:22:05
9
+ ExitNode 0D12D8E72DED99EE31BB0C57789352BED0CEEEFF
10
+ Published 2026-12-02 14:12:42
11
+ LastStatus 2026-12-02 16:00:00
12
+ ExitAddress 109.70.100.4 2026-12-02 16:05:40
13
+ ExitNode GTTDBIYLGGDYJIZQ7F0FZJVC0PNSTGYIGF4ERLE3
14
+ Published 2026-12-02 14:12:42
15
+ LastStatus 2026-12-02 16:00:00
16
+ ExitAddress 109.70.100.4 2026-12-02 16:05:40
@@ -0,0 +1,34 @@
1
+ import io
2
+ import os
3
+ from pathlib import Path
4
+
5
+ import requests
6
+
7
+ from torblock.cli import parse_response
8
+
9
+ # File containing a modified sample from of the official Tor exit node data
10
+ FIXTURE_FILE = os.path.join(os.path.dirname(__file__), "fixtures", "exitnode-data.txt")
11
+
12
+
13
+ # Parse the simulated data and validate that node IPv4 addresses can be
14
+ # extracted
15
+ def test_parse_response() -> None:
16
+ raw_bytes = Path(FIXTURE_FILE).read_bytes()
17
+
18
+ # Construct a response from the modified sample data
19
+ resp = requests.Response()
20
+ resp.status_code = 200
21
+ resp.encoding = "utf-8"
22
+ resp._content = raw_bytes
23
+ resp.raw = io.BytesIO(raw_bytes)
24
+ resp._content = raw_bytes
25
+
26
+ # Call torblock.cli to parse the data and return the set of unique exit
27
+ # node IPs
28
+ unique_nodes = parse_response(resp)
29
+
30
+ # The resp.ok value is not tested with an assert() because the response is
31
+ # not simulated. It is hardcoded.
32
+
33
+ # Compare the parsed nodes to this set to verify that they match
34
+ assert unique_nodes == set(["171.25.193.25", "80.67.167.81", "109.70.100.4"])
@@ -0,0 +1,35 @@
1
+ from torblock.cli import ipv4_addr, public_ipaddr
2
+
3
+
4
+ # Verify that the ipv4_addr function is correctly testing for valid ipv4 ips
5
+ def test_ipv4_addr() -> None:
6
+ ip_test_1 = "192.14.7.3710"
7
+ ip_test_2 = "171.25.193.25"
8
+ ip_test_3 = "127.O.O.1"
9
+
10
+ assert not ipv4_addr(ip_test_1)
11
+ assert ipv4_addr(ip_test_2)
12
+ assert not ipv4_addr(ip_test_3)
13
+
14
+
15
+ # Verify that the public_ipaddr function is correctly testing each valid ipv4
16
+ # ip to make sure it is a public address
17
+ def test_public_ipaddr() -> None:
18
+
19
+ # valid public exit ip
20
+ assert public_ipaddr("171.25.193.25")
21
+ # loopback
22
+ assert not public_ipaddr("127.0.0.1")
23
+ assert not public_ipaddr("127.0.14.7")
24
+ # private
25
+ assert not public_ipaddr("10.10.14.7")
26
+ assert not public_ipaddr("192.168.0.100")
27
+ # multicast
28
+ assert not public_ipaddr("224.28.14.7")
29
+ # local-link
30
+ assert not public_ipaddr("169.254.14.7")
31
+ # reserved
32
+ assert not public_ipaddr("240.28.14.7")
33
+ assert not public_ipaddr("255.255.255.255")
34
+ # unspecified
35
+ assert not public_ipaddr("0.0.0.0")