From a really long time, I wanted to write automation using the Tor Web Browser. My preferred automation framework is Selenium WebDriver. However, I found out that there isn’t a built-in integration between the two. I wasted almost half a day to discover how to combine them. Finally, I did it! You can find my discoveries below about the Selenium Tor integration.

What is Tor?

Tor is free software and an open network that helps you defend against traffic analysis, a form of network surveillance that threatens personal freedom and privacy, confidential business activities and relationships, and state security.

It was originally developed with the U.S. Navy in mind, for the primary purpose of protecting government communications. Today, it is used every day for a wide variety of purposes by normal people, the military, journalists, law enforcement officers, activists, and many others.

As you can see Tor is a modified Firefox browser. You have all features of Firefox plus additional protection.

Selenium Tor Integration WebDriver C# Code

In order to accomplish Selenium Tor integration, you first need to setup Firefox to use the Tor proxy. You cannot start the Tor browser using IWebDriver interface because there isn’t an implementation for it. Once started the proxy generated by Tor can be accessed via “127.0.0.1 9051“. So the first step in the plan is to start a new instance of Тоr. Next, we start a new FirefoxDriver configured with a new profile with the proxy settings generated by Tor.

By default, Tor is installed on your desktop. We start a new process of the browser which we kill in the test cleanup. The SetPreference method configures the Firefox profile to use the Tor’s proxy settings. You can validate the setup via the test below, just change the IP address with yours. The test will open whatismyipaddress site and will verify that your FirefoxDriver is running with different IP.

Change Tor Identity via Code

As you know this special browser allows you to change your identity (IP address) via the magic Tor button.

However, it’s possible to do it via telnet or C# code.

In the following folder “C:\Users\{your_user}\Desktop\Tor Browser\Browser\TorBrowser\Data\Tor“, you are going to find torrc-defaults file (config file). If you want use password authentication, you need to generate a password hash. You can do it via the tor.exe –hash-password “your_password” command.

Then open the torrc-defaults file and add the following line:

The string after hashedControlPassword is the hash generated for your password.

Your file should be similar to this:

Now you can use the following C# code to refresh the proxy settings.