The only possible way to avoid malicious exit nodes with a 100% certainty is by whitelisting the exit nodes you know for sure are not malicious (i.e. those that are under your control). The way to do that is by adding the following line in the torrc file as described in the manual:
ExitNodes node1,node2,node3...
Otherwise, the risks of using a malicious exit node can be reduced by activating the "Safest" security mode on the Tor Browser (which disables Javascript) and accessing only HTTPS websites the private key of which is not under the control of the attacker (that probably excludes nation-state adversaries, who could have the means to convince Certification Authorities to share the intermediate certificates' private keys with them and generate their own "valid" SSL certificates).
It is also advisable to use Tails or QubesOS disposable virtual machines to prevent the attacker from gaining persistence once the attack has been successful.
Onion services, though, don't use exit nodes at all, as the mechanism to build the circuits to them is a slightly different:
- It only relies on regular Tor Relays (See Onion Services' docs)
- The circuits are encrypted end-to-end from your Tor process to the Onion services' Tor process
- The encryption is authenticated by design and doesn't depend on any third-party Certification Authorities, as the Onion addresses themselves are a portion of the Onion service's hashed public key or even are the entire public key itself (v3 addresses, See section 1.2 of the spec).
This means that, with Onion services, a wannabe tamperer or eavesdropper only has three options:
- Cracking the Onion service's private key
- Hacking the Onion service's server in order to get the private key
- Setting up a different Onion service as a proxy and convincing the world his Onion address is the genuine one.
It should be noted that, aside from the Exit Nodes, the services themselves -Onion or not- can be malicious too, so keeping the "Safest" security mode turned on is always a good practice.