onionshare_cli 2.6.1__py3-none-any.whl

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.
Files changed (48) hide show
  1. onionshare_cli/__init__.py +538 -0
  2. onionshare_cli/censorship.py +311 -0
  3. onionshare_cli/common.py +624 -0
  4. onionshare_cli/meek.py +199 -0
  5. onionshare_cli/mode_settings.py +150 -0
  6. onionshare_cli/onion.py +964 -0
  7. onionshare_cli/onionshare.py +91 -0
  8. onionshare_cli/resources/static/css/style.css +432 -0
  9. onionshare_cli/resources/static/img/ajax.gif +0 -0
  10. onionshare_cli/resources/static/img/favicon.ico +0 -0
  11. onionshare_cli/resources/static/img/logo.png +0 -0
  12. onionshare_cli/resources/static/img/logo_large.png +0 -0
  13. onionshare_cli/resources/static/img/web_file.png +0 -0
  14. onionshare_cli/resources/static/img/web_folder.png +0 -0
  15. onionshare_cli/resources/static/js/chat.js +188 -0
  16. onionshare_cli/resources/static/js/jquery-3.5.1.min.js +2 -0
  17. onionshare_cli/resources/static/js/receive.js +141 -0
  18. onionshare_cli/resources/static/js/send.js +79 -0
  19. onionshare_cli/resources/static/js/socket.io.js +9 -0
  20. onionshare_cli/resources/static/js/socket.io.min.js +7 -0
  21. onionshare_cli/resources/templates/403.html +21 -0
  22. onionshare_cli/resources/templates/404.html +21 -0
  23. onionshare_cli/resources/templates/405.html +21 -0
  24. onionshare_cli/resources/templates/500.html +21 -0
  25. onionshare_cli/resources/templates/chat.html +47 -0
  26. onionshare_cli/resources/templates/denied.html +14 -0
  27. onionshare_cli/resources/templates/listing.html +60 -0
  28. onionshare_cli/resources/templates/receive.html +66 -0
  29. onionshare_cli/resources/templates/send.html +70 -0
  30. onionshare_cli/resources/templates/thankyou.html +27 -0
  31. onionshare_cli/resources/torrc_template +12 -0
  32. onionshare_cli/resources/torrc_template-meek_lite_azure +2 -0
  33. onionshare_cli/resources/torrc_template-obfs4 +12 -0
  34. onionshare_cli/resources/torrc_template-snowflake +3 -0
  35. onionshare_cli/resources/version.txt +1 -0
  36. onionshare_cli/resources/wordlist.txt +7776 -0
  37. onionshare_cli/settings.py +209 -0
  38. onionshare_cli/web/__init__.py +21 -0
  39. onionshare_cli/web/chat_mode.py +190 -0
  40. onionshare_cli/web/receive_mode.py +630 -0
  41. onionshare_cli/web/send_base_mode.py +360 -0
  42. onionshare_cli/web/share_mode.py +599 -0
  43. onionshare_cli/web/web.py +409 -0
  44. onionshare_cli/web/website_mode.py +122 -0
  45. onionshare_cli-2.6.1.dist-info/METADATA +44 -0
  46. onionshare_cli-2.6.1.dist-info/RECORD +48 -0
  47. onionshare_cli-2.6.1.dist-info/WHEEL +4 -0
  48. onionshare_cli-2.6.1.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,964 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ OnionShare | https://onionshare.org/
4
+
5
+ Copyright (C) 2014-2022 Micah Lee, et al. <micah@micahflee.com>
6
+
7
+ This program is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ (at your option) any later version.
11
+
12
+ This program is distributed in the hope that it will be useful,
13
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ GNU General Public License for more details.
16
+
17
+ You should have received a copy of the GNU General Public License
18
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
19
+ """
20
+
21
+ from .censorship import CensorshipCircumvention
22
+ from .meek import Meek
23
+ from stem.control import Controller
24
+ from stem import ProtocolError, SocketClosed
25
+ from stem.connection import MissingPassword, UnreadableCookieFile, AuthenticationFailure
26
+ import base64
27
+ import nacl.public
28
+ import os
29
+ import psutil
30
+ import shlex
31
+ import subprocess
32
+ import tempfile
33
+ import time
34
+ import traceback
35
+
36
+ from distutils.version import LooseVersion as Version
37
+
38
+
39
+ class TorErrorAutomatic(Exception):
40
+ """
41
+ OnionShare is failing to connect and authenticate to the Tor controller,
42
+ using automatic settings that should work with Tor Browser.
43
+ """
44
+
45
+
46
+ class TorErrorInvalidSetting(Exception):
47
+ """
48
+ This exception is raised if the settings just don't make sense.
49
+ """
50
+
51
+
52
+ class TorErrorSocketPort(Exception):
53
+ """
54
+ OnionShare can't connect to the Tor controller using the supplied address and port.
55
+ """
56
+
57
+
58
+ class TorErrorSocketFile(Exception):
59
+ """
60
+ OnionShare can't connect to the Tor controller using the supplied socket file.
61
+ """
62
+
63
+
64
+ class TorErrorMissingPassword(Exception):
65
+ """
66
+ OnionShare connected to the Tor controller, but it requires a password.
67
+ """
68
+
69
+
70
+ class TorErrorUnreadableCookieFile(Exception):
71
+ """
72
+ OnionShare connected to the Tor controller, but your user does not have permission
73
+ to access the cookie file.
74
+ """
75
+
76
+
77
+ class TorErrorAuthError(Exception):
78
+ """
79
+ OnionShare connected to the address and port, but can't authenticate. It's possible
80
+ that a Tor controller isn't listening on this port.
81
+ """
82
+
83
+
84
+ class TorErrorProtocolError(Exception):
85
+ """
86
+ This exception is raised if onionshare connects to the Tor controller, but it
87
+ isn't acting like a Tor controller (such as in Whonix).
88
+ """
89
+
90
+
91
+ class TorTooOldEphemeral(Exception):
92
+ """
93
+ This exception is raised if the version of tor doesn't support ephemeral onion services
94
+ """
95
+
96
+
97
+ class TorTooOldStealth(Exception):
98
+ """
99
+ This exception is raised if the version of tor doesn't support stealth onion services
100
+ """
101
+
102
+
103
+ class BundledTorTimeout(Exception):
104
+ """
105
+ This exception is raised if onionshare is set to use the bundled Tor binary,
106
+ but Tor doesn't finish connecting promptly.
107
+ """
108
+
109
+
110
+ class BundledTorCanceled(Exception):
111
+ """
112
+ This exception is raised if onionshare is set to use the bundled Tor binary,
113
+ and the user cancels connecting to Tor
114
+ """
115
+
116
+
117
+ class BundledTorBroken(Exception):
118
+ """
119
+ This exception is raised if onionshare is set to use the bundled Tor binary,
120
+ but the process seems to fail to run.
121
+ """
122
+
123
+
124
+ class PortNotAvailable(Exception):
125
+ """
126
+ There are no available ports for OnionShare to use, which really shouldn't ever happen
127
+ """
128
+
129
+
130
+ class Onion(object):
131
+ """
132
+ Onion is an abstraction layer for connecting to the Tor control port and
133
+ creating onion services. OnionShare supports creating onion services by
134
+ connecting to the Tor controller and using ADD_ONION, DEL_ONION.
135
+
136
+ stealth: Should the onion service be stealth?
137
+
138
+ settings: A Settings object. If it's not passed in, load from disk.
139
+
140
+ bundled_connection_func: If the tor connection type is bundled, optionally
141
+ call this function and pass in a status string while connecting to tor. This
142
+ is necessary for status updates to reach the GUI.
143
+ """
144
+
145
+ def __init__(self, common, use_tmp_dir=False, get_tor_paths=None):
146
+ self.common = common
147
+ self.common.log("Onion", "__init__")
148
+
149
+ self.use_tmp_dir = use_tmp_dir
150
+
151
+ # Set the path of the tor binary, for bundled tor
152
+ if not get_tor_paths:
153
+ get_tor_paths = self.common.get_tor_paths
154
+ (
155
+ self.tor_path,
156
+ self.tor_geo_ip_file_path,
157
+ self.tor_geo_ipv6_file_path,
158
+ self.obfs4proxy_file_path,
159
+ self.snowflake_file_path,
160
+ self.meek_client_file_path,
161
+ ) = get_tor_paths()
162
+
163
+ # The tor process
164
+ self.tor_proc = None
165
+
166
+ # The Tor controller
167
+ self.c = None
168
+
169
+ # Start out not connected to Tor
170
+ self.connected_to_tor = False
171
+
172
+ # Assigned later if we are using stealth mode
173
+ self.auth_string = None
174
+
175
+ # Keep track of onions where it's important to gracefully close to prevent truncated downloads
176
+ self.graceful_close_onions = []
177
+
178
+ def key_str(self, key):
179
+ """
180
+ Returns a base32 decoded string of a key.
181
+ """
182
+ # bytes to base 32
183
+ key_bytes = bytes(key)
184
+ key_b32 = base64.b32encode(key_bytes)
185
+ # strip trailing ====
186
+ assert key_b32[-4:] == b"===="
187
+ key_b32 = key_b32[:-4]
188
+ # change from b'ASDF' to ASDF
189
+ s = key_b32.decode("utf-8")
190
+ return s
191
+
192
+ def connect(
193
+ self,
194
+ custom_settings=None,
195
+ config=None,
196
+ tor_status_update_func=None,
197
+ connect_timeout=120,
198
+ local_only=False,
199
+ ):
200
+ if local_only:
201
+ self.common.log(
202
+ "Onion", "connect", "--local-only, so skip trying to connect"
203
+ )
204
+ return
205
+
206
+ # Either use settings that are passed in, or use them from common
207
+ if custom_settings:
208
+ self.settings = custom_settings
209
+ elif config:
210
+ self.common.load_settings(config)
211
+ self.settings = self.common.settings
212
+ else:
213
+ self.common.load_settings()
214
+ self.settings = self.common.settings
215
+
216
+ self.common.log(
217
+ "Onion",
218
+ "connect",
219
+ f"connection_type={self.settings.get('connection_type')}",
220
+ )
221
+
222
+ # The Tor controller
223
+ self.c = None
224
+
225
+ if self.settings.get("connection_type") == "bundled":
226
+ # Create a torrc for this session
227
+ if self.use_tmp_dir:
228
+ self.tor_data_directory = tempfile.TemporaryDirectory(
229
+ dir=self.common.build_tmp_dir()
230
+ )
231
+ self.tor_data_directory_name = self.tor_data_directory.name
232
+ else:
233
+ self.tor_data_directory_name = self.common.build_tor_dir()
234
+ self.common.log(
235
+ "Onion",
236
+ "connect",
237
+ f"tor_data_directory_name={self.tor_data_directory_name}",
238
+ )
239
+
240
+ # Create the torrc
241
+ with open(self.common.get_resource_path("torrc_template")) as f:
242
+ torrc_template = f.read()
243
+ self.tor_cookie_auth_file = os.path.join(
244
+ self.tor_data_directory_name, "cookie"
245
+ )
246
+ try:
247
+ self.tor_socks_port = self.common.get_available_port(1000, 65535)
248
+ except Exception:
249
+ print("OnionShare port not available")
250
+ raise PortNotAvailable()
251
+ self.tor_torrc = os.path.join(self.tor_data_directory_name, "torrc")
252
+
253
+ # If there is an existing OnionShare tor process, kill it
254
+ for proc in psutil.process_iter(["pid", "name", "username"]):
255
+ try:
256
+ cmdline = proc.cmdline()
257
+ if (
258
+ cmdline[0] == self.tor_path
259
+ and cmdline[1] == "-f"
260
+ and cmdline[2] == self.tor_torrc
261
+ ):
262
+ self.common.log(
263
+ "Onion", "connect", "found a stale tor process, killing it"
264
+ )
265
+ proc.terminate()
266
+ proc.wait()
267
+ break
268
+ except Exception:
269
+ pass
270
+
271
+ if self.common.platform == "Windows" or self.common.platform == "Darwin":
272
+ # Windows doesn't support unix sockets, so it must use a network port.
273
+ # macOS can't use unix sockets either because socket filenames are limited to
274
+ # 100 chars, and the macOS sandbox forces us to put the socket file in a place
275
+ # with a really long path.
276
+ torrc_template += "ControlPort {{control_port}}\n"
277
+ try:
278
+ self.tor_control_port = self.common.get_available_port(1000, 65535)
279
+ except Exception:
280
+ print("OnionShare port not available")
281
+ raise PortNotAvailable()
282
+ self.tor_control_socket = None
283
+ else:
284
+ # Linux and BSD can use unix sockets
285
+ torrc_template += "ControlSocket {{control_socket}}\n"
286
+ self.tor_control_port = None
287
+ self.tor_control_socket = os.path.join(
288
+ self.tor_data_directory_name, "control_socket"
289
+ )
290
+
291
+ torrc_template = torrc_template.replace(
292
+ "{{data_directory}}", self.tor_data_directory_name
293
+ )
294
+ torrc_template = torrc_template.replace(
295
+ "{{control_port}}", str(self.tor_control_port)
296
+ )
297
+ torrc_template = torrc_template.replace(
298
+ "{{control_socket}}", str(self.tor_control_socket)
299
+ )
300
+ torrc_template = torrc_template.replace(
301
+ "{{cookie_auth_file}}", self.tor_cookie_auth_file
302
+ )
303
+ torrc_template = torrc_template.replace(
304
+ "{{geo_ip_file}}", self.tor_geo_ip_file_path
305
+ )
306
+ torrc_template = torrc_template.replace(
307
+ "{{geo_ipv6_file}}", self.tor_geo_ipv6_file_path
308
+ )
309
+ torrc_template = torrc_template.replace(
310
+ "{{socks_port}}", str(self.tor_socks_port)
311
+ )
312
+ torrc_template = torrc_template.replace(
313
+ "{{obfs4proxy_path}}", str(self.obfs4proxy_file_path)
314
+ )
315
+ torrc_template = torrc_template.replace(
316
+ "{{snowflake_path}}", str(self.snowflake_file_path)
317
+ )
318
+
319
+ with open(self.tor_torrc, "w") as f:
320
+ self.common.log("Onion", "connect", "Writing torrc template file")
321
+ f.write(torrc_template)
322
+
323
+ # Bridge support
324
+ if self.settings.get("bridges_enabled"):
325
+ f.write("\nUseBridges 1\n")
326
+ if self.settings.get("bridges_type") == "built-in":
327
+ use_torrc_bridge_templates = False
328
+ builtin_bridge_type = self.settings.get("bridges_builtin_pt")
329
+ # Use built-inbridges stored in settings, if they are there already.
330
+ # They are probably newer than that of our hardcoded copies.
331
+ if self.settings.get("bridges_builtin"):
332
+ try:
333
+ for line in self.settings.get("bridges_builtin")[
334
+ builtin_bridge_type
335
+ ]:
336
+ if line.strip() != "":
337
+ f.write(f"Bridge {line}\n")
338
+ self.common.log(
339
+ "Onion",
340
+ "connect",
341
+ "Wrote in the built-in bridges from OnionShare settings",
342
+ )
343
+ except KeyError:
344
+ # Somehow we had built-in bridges in our settings, but
345
+ # not for this bridge type. Fall back to using the hard-
346
+ # coded templates.
347
+ use_torrc_bridge_templates = True
348
+ else:
349
+ use_torrc_bridge_templates = True
350
+ if use_torrc_bridge_templates:
351
+ if builtin_bridge_type == "obfs4":
352
+ with open(
353
+ self.common.get_resource_path(
354
+ "torrc_template-obfs4"
355
+ )
356
+ ) as o:
357
+ f.write(o.read())
358
+ elif builtin_bridge_type == "meek-azure":
359
+ with open(
360
+ self.common.get_resource_path(
361
+ "torrc_template-meek_lite_azure"
362
+ )
363
+ ) as o:
364
+ f.write(o.read())
365
+ elif builtin_bridge_type == "snowflake":
366
+ with open(
367
+ self.common.get_resource_path(
368
+ "torrc_template-snowflake"
369
+ )
370
+ ) as o:
371
+ f.write(o.read())
372
+ self.common.log(
373
+ "Onion",
374
+ "connect",
375
+ "Wrote in the built-in bridges from torrc templates",
376
+ )
377
+ elif self.settings.get("bridges_type") == "moat":
378
+ for line in self.settings.get("bridges_moat").split("\n"):
379
+ if line.strip() != "":
380
+ f.write(f"Bridge {line}\n")
381
+
382
+ elif self.settings.get("bridges_type") == "custom":
383
+ for line in self.settings.get("bridges_custom").split("\n"):
384
+ if line.strip() != "":
385
+ f.write(f"Bridge {line}\n")
386
+
387
+ # Execute a tor subprocess
388
+ self.common.log("Onion", "connect", f"starting {self.tor_path} subprocess")
389
+ start_ts = time.time()
390
+ if self.common.platform == "Windows":
391
+ # In Windows, hide console window when opening tor.exe subprocess
392
+ startupinfo = subprocess.STARTUPINFO()
393
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
394
+ self.tor_proc = subprocess.Popen(
395
+ [self.tor_path, "-f", self.tor_torrc],
396
+ stdout=subprocess.PIPE,
397
+ stderr=subprocess.PIPE,
398
+ startupinfo=startupinfo,
399
+ )
400
+ else:
401
+ if self.common.is_snapcraft():
402
+ env = None
403
+ else:
404
+ env = {"LD_LIBRARY_PATH": os.path.dirname(self.tor_path)}
405
+
406
+ self.tor_proc = subprocess.Popen(
407
+ [self.tor_path, "-f", self.tor_torrc],
408
+ stdout=subprocess.PIPE,
409
+ stderr=subprocess.PIPE,
410
+ env=env,
411
+ )
412
+
413
+ # Wait for the tor controller to start
414
+ self.common.log("Onion", "connect", f"tor pid: {self.tor_proc.pid}")
415
+ time.sleep(2)
416
+
417
+ return_code = self.tor_proc.poll()
418
+ if return_code != None:
419
+ self.common.log("Onion", "connect", f"tor process has terminated early: {return_code}")
420
+
421
+ # Connect to the controller
422
+ self.common.log("Onion", "connect", "authenticating to tor controller")
423
+ try:
424
+ if (
425
+ self.common.platform == "Windows"
426
+ or self.common.platform == "Darwin"
427
+ ):
428
+ self.c = Controller.from_port(port=self.tor_control_port)
429
+ self.c.authenticate()
430
+ else:
431
+ self.c = Controller.from_socket_file(path=self.tor_control_socket)
432
+ self.c.authenticate()
433
+ except Exception as e:
434
+ print("OnionShare could not connect to Tor:\n{}".format(e.args[0]))
435
+ print(traceback.format_exc())
436
+ raise BundledTorBroken(e.args[0])
437
+
438
+ while True:
439
+ try:
440
+ res = self.c.get_info("status/bootstrap-phase")
441
+ except SocketClosed:
442
+ raise BundledTorCanceled()
443
+
444
+ res_parts = shlex.split(res)
445
+ progress = res_parts[2].split("=")[1]
446
+ summary = res_parts[4].split("=")[1]
447
+
448
+ # "\033[K" clears the rest of the line
449
+ print(
450
+ f"\rConnecting to the Tor network: {progress}% - {summary}\033[K",
451
+ end="",
452
+ )
453
+
454
+ if callable(tor_status_update_func):
455
+ if not tor_status_update_func(progress, summary):
456
+ # If the dialog was canceled, stop connecting to Tor
457
+ self.common.log(
458
+ "Onion",
459
+ "connect",
460
+ "tor_status_update_func returned false, canceling connecting to Tor",
461
+ )
462
+ print()
463
+ return False
464
+
465
+ if summary == "Done":
466
+ print("")
467
+ break
468
+ time.sleep(0.2)
469
+
470
+ # If using bridges, it might take a bit longer to connect to Tor
471
+ if self.settings.get("bridges_enabled"):
472
+ # Only override timeout if a custom timeout has not been passed in
473
+ if connect_timeout == 120:
474
+ connect_timeout = 150
475
+ if time.time() - start_ts > connect_timeout:
476
+ print("")
477
+ try:
478
+ self.tor_proc.terminate()
479
+ print(
480
+ "Taking too long to connect to Tor. Maybe you aren't connected to the Internet, or have an inaccurate system clock?"
481
+ )
482
+ raise BundledTorTimeout()
483
+ except FileNotFoundError:
484
+ pass
485
+
486
+ elif self.settings.get("connection_type") == "automatic":
487
+ # Automatically try to guess the right way to connect to Tor Browser
488
+ automatic_error = "Could not connect to the Tor controller. Is Tor Browser (available from torproject.org) running in the background?"
489
+
490
+ # Try connecting to control port
491
+ found_tor = False
492
+
493
+ # If the TOR_CONTROL_PORT environment variable is set, use that
494
+ env_port = os.environ.get("TOR_CONTROL_PORT")
495
+ if env_port:
496
+ try:
497
+ self.c = Controller.from_port(port=int(env_port))
498
+ found_tor = True
499
+ except Exception:
500
+ pass
501
+
502
+ else:
503
+ # Otherwise, try default ports for Tor Browser, Tor Messenger, and system tor
504
+ try:
505
+ ports = [9151, 9153, 9051]
506
+ for port in ports:
507
+ self.c = Controller.from_port(port=port)
508
+ found_tor = True
509
+ except Exception:
510
+ pass
511
+
512
+ # If this still didn't work, try guessing the default socket file path
513
+ socket_file_path = ""
514
+ if not found_tor:
515
+ try:
516
+ if self.common.platform == "Darwin":
517
+ socket_file_path = os.path.expanduser(
518
+ "~/Library/Application Support/TorBrowser-Data/Tor/control.socket"
519
+ )
520
+
521
+ self.c = Controller.from_socket_file(path=socket_file_path)
522
+ found_tor = True
523
+ except Exception:
524
+ pass
525
+
526
+ # If connecting to default control ports failed, so let's try
527
+ # guessing the socket file name next
528
+ if not found_tor:
529
+ try:
530
+ if self.common.platform == "Linux" or self.common.platform == "BSD":
531
+ socket_file_path = (
532
+ f"/run/user/{os.geteuid()}/Tor/control.socket"
533
+ )
534
+ elif self.common.platform == "Darwin":
535
+ socket_file_path = (
536
+ f"/run/user/{os.geteuid()}/Tor/control.socket"
537
+ )
538
+ elif self.common.platform == "Windows":
539
+ # Windows doesn't support unix sockets
540
+ print(automatic_error)
541
+ raise TorErrorAutomatic()
542
+
543
+ self.c = Controller.from_socket_file(path=socket_file_path)
544
+
545
+ except Exception:
546
+ print(automatic_error)
547
+ raise TorErrorAutomatic()
548
+
549
+ # Try authenticating
550
+ try:
551
+ self.c.authenticate()
552
+ except Exception:
553
+ print(automatic_error)
554
+ raise TorErrorAutomatic()
555
+
556
+ else:
557
+ # Use specific settings to connect to tor
558
+ invalid_settings_error = "Can't connect to Tor controller because your settings don't make sense."
559
+
560
+ # Try connecting
561
+ try:
562
+ if self.settings.get("connection_type") == "control_port":
563
+ self.c = Controller.from_port(
564
+ address=self.settings.get("control_port_address"),
565
+ port=self.settings.get("control_port_port"),
566
+ )
567
+ elif self.settings.get("connection_type") == "socket_file":
568
+ self.c = Controller.from_socket_file(
569
+ path=self.settings.get("socket_file_path")
570
+ )
571
+ else:
572
+ print(invalid_settings_error)
573
+ raise TorErrorInvalidSetting()
574
+
575
+ except Exception:
576
+ if self.settings.get("connection_type") == "control_port":
577
+ print(
578
+ "Can't connect to the Tor controller at {}:{}.".format(
579
+ self.settings.get("control_port_address"),
580
+ self.settings.get("control_port_port"),
581
+ )
582
+ )
583
+ raise TorErrorSocketPort(
584
+ self.settings.get("control_port_address"),
585
+ self.settings.get("control_port_port"),
586
+ )
587
+ print(
588
+ "Can't connect to the Tor controller using socket file {}.".format(
589
+ self.settings.get("socket_file_path")
590
+ )
591
+ )
592
+ raise TorErrorSocketFile(self.settings.get("socket_file_path"))
593
+
594
+ # Try authenticating
595
+ try:
596
+ if self.settings.get("auth_type") == "no_auth":
597
+ self.c.authenticate()
598
+ elif self.settings.get("auth_type") == "password":
599
+ self.c.authenticate(self.settings.get("auth_password"))
600
+ else:
601
+ print(invalid_settings_error)
602
+ raise TorErrorInvalidSetting()
603
+
604
+ except MissingPassword:
605
+ print(
606
+ "Connected to Tor controller, but it requires a password to authenticate."
607
+ )
608
+ raise TorErrorMissingPassword()
609
+ except UnreadableCookieFile:
610
+ print(
611
+ "Connected to the Tor controller, but password may be wrong, or your user is not permitted to read the cookie file."
612
+ )
613
+ raise TorErrorUnreadableCookieFile()
614
+ except AuthenticationFailure:
615
+ print(
616
+ "Connected to {}:{}, but can't authenticate. Maybe this isn't a Tor controller?".format(
617
+ self.settings.get("control_port_address"),
618
+ self.settings.get("control_port_port"),
619
+ )
620
+ )
621
+ raise TorErrorAuthError(
622
+ self.settings.get("control_port_address"),
623
+ self.settings.get("control_port_port"),
624
+ )
625
+
626
+ # If we made it this far, we should be connected to Tor
627
+ self.connected_to_tor = True
628
+
629
+ # Get the tor version
630
+ self.tor_version = self.c.get_version().version_str
631
+ self.common.log("Onion", "connect", f"Connected to tor {self.tor_version}")
632
+
633
+ # Do the versions of stem and tor that I'm using support ephemeral onion services?
634
+ list_ephemeral_hidden_services = getattr(
635
+ self.c, "list_ephemeral_hidden_services", None
636
+ )
637
+ self.supports_ephemeral = (
638
+ callable(list_ephemeral_hidden_services) and self.tor_version >= "0.2.7.1"
639
+ )
640
+
641
+ # Do the versions of stem and tor that I'm using support v3 stealth onion services?
642
+ try:
643
+ res = self.c.create_ephemeral_hidden_service(
644
+ {1: 1},
645
+ basic_auth=None,
646
+ await_publication=False,
647
+ key_type="NEW",
648
+ key_content="ED25519-V3",
649
+ client_auth_v3="E2GOT5LTUTP3OAMRCRXO4GSH6VKJEUOXZQUC336SRKAHTTT5OVSA",
650
+ )
651
+ tmp_service_id = res.service_id
652
+ self.c.remove_ephemeral_hidden_service(tmp_service_id)
653
+ self.supports_stealth = True
654
+ except Exception:
655
+ # ephemeral stealth onion services are not supported
656
+ self.supports_stealth = False
657
+
658
+ # Does this version of Tor support next-gen ('v3') onions?
659
+ # Note, this is the version of Tor where this bug was fixed:
660
+ # https://trac.torproject.org/projects/tor/ticket/28619
661
+ self.supports_v3_onions = self.tor_version >= Version("0.3.5.7")
662
+
663
+ # Now that we are connected to Tor, if we are using built-in bridges,
664
+ # update them with the latest copy available from the Tor API
665
+ if (
666
+ self.settings.get("bridges_enabled")
667
+ and self.settings.get("bridges_type") == "built-in"
668
+ ):
669
+ self.update_builtin_bridges()
670
+
671
+ def is_authenticated(self):
672
+ """
673
+ Returns True if the Tor connection is still working, or False otherwise.
674
+ """
675
+ if self.c is not None:
676
+ return self.c.is_authenticated()
677
+ else:
678
+ return False
679
+
680
+ def start_onion_service(self, mode, mode_settings, port, await_publication):
681
+ """
682
+ Start a onion service on port 80, pointing to the given port, and
683
+ return the onion hostname.
684
+ """
685
+ self.common.log("Onion", "start_onion_service", f"port={port}")
686
+
687
+ if not self.supports_ephemeral:
688
+ print(
689
+ "Your version of Tor is too old, ephemeral onion services are not supported"
690
+ )
691
+ raise TorTooOldEphemeral()
692
+
693
+ if mode_settings.get("onion", "private_key"):
694
+ key_content = mode_settings.get("onion", "private_key")
695
+ key_type = "ED25519-V3"
696
+ else:
697
+ key_content = "ED25519-V3"
698
+ key_type = "NEW"
699
+
700
+ debug_message = f"key_type={key_type}"
701
+ if key_type == "NEW":
702
+ debug_message += f", key_content={key_content}"
703
+ self.common.log("Onion", "start_onion_service", debug_message)
704
+
705
+ if mode_settings.get("general", "public"):
706
+ client_auth_priv_key = None
707
+ client_auth_pub_key = None
708
+ else:
709
+ if not self.supports_stealth:
710
+ print(
711
+ "Your version of Tor is too old, stealth onion services are not supported"
712
+ )
713
+ raise TorTooOldStealth()
714
+ else:
715
+ if key_type == "NEW" or not mode_settings.get(
716
+ "onion", "client_auth_priv_key"
717
+ ):
718
+ # Generate a new key pair for Client Auth on new onions, or if
719
+ # it's a persistent onion but for some reason we don't them
720
+ client_auth_priv_key_raw = nacl.public.PrivateKey.generate()
721
+ client_auth_priv_key = self.key_str(client_auth_priv_key_raw)
722
+ client_auth_pub_key = self.key_str(
723
+ client_auth_priv_key_raw.public_key
724
+ )
725
+ else:
726
+ # These should have been saved in settings from the previous run of a persistent onion
727
+ client_auth_priv_key = mode_settings.get(
728
+ "onion", "client_auth_priv_key"
729
+ )
730
+ client_auth_pub_key = mode_settings.get(
731
+ "onion", "client_auth_pub_key"
732
+ )
733
+
734
+ try:
735
+ if not self.supports_stealth:
736
+ res = self.c.create_ephemeral_hidden_service(
737
+ {80: port},
738
+ await_publication=await_publication,
739
+ basic_auth=None,
740
+ key_type=key_type,
741
+ key_content=key_content,
742
+ )
743
+ else:
744
+ res = self.c.create_ephemeral_hidden_service(
745
+ {80: port},
746
+ await_publication=await_publication,
747
+ basic_auth=None,
748
+ key_type=key_type,
749
+ key_content=key_content,
750
+ client_auth_v3=client_auth_pub_key,
751
+ )
752
+
753
+ except ProtocolError as e:
754
+ print("Tor error: {}".format(e.args[0]))
755
+ raise TorErrorProtocolError(e.args[0])
756
+
757
+ onion_host = res.service_id + ".onion"
758
+
759
+ # Gracefully close share mode rendezvous circuits
760
+ if mode == "share":
761
+ self.graceful_close_onions.append(res.service_id)
762
+
763
+ # Save the service_id
764
+ mode_settings.set("general", "service_id", res.service_id)
765
+
766
+ # Save the private key and hidservauth string
767
+ if not mode_settings.get("onion", "private_key"):
768
+ mode_settings.set("onion", "private_key", res.private_key)
769
+
770
+ # If using V3 onions and Client Auth, save both the private and public key
771
+ # because we need to send the public key to ADD_ONION (if we restart this
772
+ # same share at a later date), and the private key to the other user for
773
+ # their Tor Browser.
774
+ if not mode_settings.get("general", "public"):
775
+ mode_settings.set("onion", "client_auth_priv_key", client_auth_priv_key)
776
+ mode_settings.set("onion", "client_auth_pub_key", client_auth_pub_key)
777
+ # If we were pasting the client auth directly into the filesystem behind a Tor client,
778
+ # it would need to be in the format below. However, let's just set the private key
779
+ # by itself, as this can be pasted directly into Tor Browser, which is likely to
780
+ # be the most common use case.
781
+ # self.auth_string = f"{onion_host}:x25519:{client_auth_priv_key}"
782
+ self.auth_string = client_auth_priv_key
783
+
784
+ return onion_host
785
+
786
+ def stop_onion_service(self, mode_settings):
787
+ """
788
+ Stop a specific onion service
789
+ """
790
+ onion_host = mode_settings.get("general", "service_id")
791
+ if onion_host:
792
+ self.common.log("Onion", "stop_onion_service", f"onion host: {onion_host}")
793
+ try:
794
+ self.c.remove_ephemeral_hidden_service(
795
+ mode_settings.get("general", "service_id")
796
+ )
797
+ except Exception:
798
+ self.common.log(
799
+ "Onion", "stop_onion_service", f"failed to remove {onion_host}"
800
+ )
801
+
802
+ def cleanup(self, stop_tor=True, wait=True):
803
+ """
804
+ Stop onion services that were created earlier. If there's a tor subprocess running, kill it.
805
+ """
806
+ self.common.log("Onion", "cleanup")
807
+
808
+ # Cleanup the ephemeral onion services, if we have any
809
+ try:
810
+ onions = self.c.list_ephemeral_hidden_services()
811
+ for service_id in onions:
812
+ onion_host = f"{service_id}.onion"
813
+ try:
814
+ self.common.log(
815
+ "Onion", "cleanup", f"trying to remove onion {onion_host}"
816
+ )
817
+ self.c.remove_ephemeral_hidden_service(service_id)
818
+ except Exception:
819
+ self.common.log(
820
+ "Onion", "cleanup", f"failed to remove onion {onion_host}"
821
+ )
822
+ pass
823
+ except Exception:
824
+ pass
825
+
826
+ if stop_tor:
827
+ # Stop tor process
828
+ if self.tor_proc:
829
+ if wait:
830
+ # Wait for Tor rendezvous circuits to close
831
+ # Catch exceptions to prevent crash on Ctrl-C
832
+ try:
833
+ rendezvous_circuit_ids = []
834
+ for c in self.c.get_circuits():
835
+ if (
836
+ c.purpose == "HS_SERVICE_REND"
837
+ and c.rend_query in self.graceful_close_onions
838
+ ):
839
+ rendezvous_circuit_ids.append(c.id)
840
+
841
+ symbols = list("\\|/-")
842
+ symbols_i = 0
843
+
844
+ while True:
845
+ num_rend_circuits = 0
846
+ for c in self.c.get_circuits():
847
+ if c.id in rendezvous_circuit_ids:
848
+ num_rend_circuits += 1
849
+
850
+ if num_rend_circuits == 0:
851
+ print(
852
+ "\rTor rendezvous circuits have closed" + " " * 20
853
+ )
854
+ break
855
+
856
+ if num_rend_circuits == 1:
857
+ circuits = "circuit"
858
+ else:
859
+ circuits = "circuits"
860
+ print(
861
+ f"\rWaiting for {num_rend_circuits} Tor rendezvous {circuits} to close {symbols[symbols_i]} ",
862
+ end="",
863
+ )
864
+ symbols_i = (symbols_i + 1) % len(symbols)
865
+ time.sleep(1)
866
+ except Exception:
867
+ pass
868
+
869
+ self.tor_proc.terminate()
870
+ time.sleep(0.2)
871
+ if self.tor_proc.poll() is None:
872
+ self.common.log(
873
+ "Onion",
874
+ "cleanup",
875
+ "Tried to terminate tor process but it's still running",
876
+ )
877
+ try:
878
+ self.tor_proc.kill()
879
+ time.sleep(0.2)
880
+ if self.tor_proc.poll() is None:
881
+ self.common.log(
882
+ "Onion",
883
+ "cleanup",
884
+ "Tried to kill tor process but it's still running",
885
+ )
886
+ except Exception:
887
+ self.common.log(
888
+ "Onion", "cleanup", "Exception while killing tor process"
889
+ )
890
+ self.tor_proc = None
891
+
892
+ # Reset other Onion settings
893
+ self.connected_to_tor = False
894
+
895
+ try:
896
+ # Delete the temporary tor data directory
897
+ if self.use_tmp_dir:
898
+ self.tor_data_directory.cleanup()
899
+ except Exception:
900
+ pass
901
+
902
+ def get_tor_socks_port(self):
903
+ """
904
+ Returns a (address, port) tuple for the Tor SOCKS port
905
+ """
906
+ self.common.log("Onion", "get_tor_socks_port")
907
+
908
+ if self.settings.get("connection_type") == "bundled":
909
+ return ("127.0.0.1", self.tor_socks_port)
910
+ elif self.settings.get("connection_type") == "automatic":
911
+ return ("127.0.0.1", 9150)
912
+ else:
913
+ return (self.settings.get("socks_address"), self.settings.get("socks_port"))
914
+
915
+ def update_builtin_bridges(self):
916
+ """
917
+ Use the CensorshipCircumvention API to fetch the latest built-in bridges
918
+ and update them in settings.
919
+ """
920
+ builtin_bridges = False
921
+ meek = None
922
+ # Try obtaining bridges over Tor, if we're connected to it.
923
+ if self.is_authenticated:
924
+ self.common.log(
925
+ "Onion",
926
+ "update_builtin_bridges",
927
+ "Updating the built-in bridges. Trying over Tor first",
928
+ )
929
+ self.censorship_circumvention = CensorshipCircumvention(
930
+ self.common, None, self
931
+ )
932
+ builtin_bridges = self.censorship_circumvention.request_builtin_bridges()
933
+
934
+ if not builtin_bridges:
935
+ # Tor was not running or it failed to hit the Tor API.
936
+ # Fall back to using Meek (domain-fronting).
937
+ self.common.log(
938
+ "Onion",
939
+ "update_builtin_bridges",
940
+ "Updating the built-in bridges. Trying via Meek (no Tor)",
941
+ )
942
+ meek = Meek(self.common)
943
+ meek.start()
944
+ self.censorship_circumvention = CensorshipCircumvention(
945
+ self.common, meek, None
946
+ )
947
+ builtin_bridges = self.censorship_circumvention.request_builtin_bridges()
948
+ meek.cleanup()
949
+
950
+ if builtin_bridges:
951
+ # If we got to this point, we have bridges
952
+ self.common.log(
953
+ "Onion",
954
+ "update_builtin_bridges",
955
+ f"Obtained bridges: {builtin_bridges}",
956
+ )
957
+ # Save the new settings
958
+ self.settings.set("bridges_builtin", builtin_bridges)
959
+ self.settings.save()
960
+ else:
961
+ self.common.log(
962
+ "Onion", "update_builtin_bridges", "Error getting built-in bridges"
963
+ )
964
+ return False