Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#

Using Selenium WebDriver with Tor C# Code

Rate me:
Please Sign up or sign in to vote.
4.91/5 (17 votes)
18 Feb 2015CPOL3 min read 60.4K   19   15
Using Selenium WebDriver with Tor C# Code

Introduction

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.

What is Tor?

Tor is a 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.

Image 1

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

Download it from here: https://www.torproject.org/

Integrate Tor and Selenium WebDriver

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.

C#
public IWebDriver Driver { get; set; }
public Process TorProcess { get; set; }
public WebDriverWait Wait { get; set; }

[TestInitialize]
public void SetupTest()
{
    String torBinaryPath = @"C:\Users\aangelov\Desktop\Tor Browser\Browser\firefox.exe";
    this.TorProcess = new Process();
    this.TorProcess.StartInfo.FileName = torBinaryPath;
    this.TorProcess.StartInfo.Arguments = "-n";
    this.TorProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
    this.TorProcess.Start();

    FirefoxProfile profile = new FirefoxProfile();
    profile.SetPreference("network.proxy.type", 1);
    profile.SetPreference("network.proxy.socks", "127.0.0.1");
    profile.SetPreference("network.proxy.socks_port", 9150);
    this.Driver = new FirefoxDriver(profile);
    this.Wait = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(60));
}

[TestCleanup]
public void TeardownTest()
{
    this.Driver.Quit();
    this.TorProcess.Kill();
}

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 http://whatismyipaddress.com/ and will verify that your FirefoxDriver is running with different IP.

C#
[TestMethod]
public void Open_Tor_Browser()
{
    this.Driver.Navigate().GoToUrl(@"http://whatismyipaddress.com/");
    var expression = By.XPath("//*[@id='section_left']/div[2]");
    this.Wait.Until(x => x.FindElement(expression));
    var element = this.Driver.FindElement(expression);
    Assert.AreNotEqual<string>("84.40.65.000", element.Text);
}

Change Tor Identity via Code

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

Image 2

However, it’s possible to do it via telnet or C# code. Use the following guide for telnet: https://stem.torproject.org/faq.html.

% telnet localhost 9051
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
AUTHENTICATE
250 OK
SIGNAL NEWNYM
250 OK

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:

hashedControlPassword 16:751C69A9B10D7F4260B04E0D07D7EBCB760EDCEBADD40CDAF40F1FB095

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

Your file should be similar to this:

# If non-zero, try to write to disk less frequently than we would otherwise.
AvoidDiskWrites 1
# Where to send logging messages.  Format is minSeverity[-maxSeverity]
# (stderr|stdout|syslog|file FILENAME).
Log notice stdout
# Bind to this address to listen to connections from SOCKS-speaking
# applications.
SocksPort 9150
ControlPort 9151
hashedControlPassword 16:751C69A9B10D7F4260B04E0D07D7EBCB760EDCEBADD40CDAF40F1FB095
CookieAuthentication 0
## fteproxy configuration
ClientTransportPlugin fte exec TorBrowser\Tor\PluggableTransports\fteproxy --managed

## obfsproxy configuration
ClientTransportPlugin obfs2,obfs3,scramblesuit exec 
TorBrowser\Tor\PluggableTransports\obfsproxy managed

## flash proxy configuration
#
# Change the second number here (9000) to the number of a port that can
# receive connections from the Internet (the port for which you
# configured port forwarding).
ClientTransportPlugin flashproxy exec TorBrowser\Tor\PluggableTransports\flashproxy-client 
	--register :0 :9000

## meek configuration
ClientTransportPlugin meek exec TorBrowser\Tor\PluggableTransports\terminateprocess-buffer 
TorBrowser\Tor\PluggableTransports\meek-client-torbrowser --exit-on-stdin-eof 
-- TorBrowser\Tor\PluggableTransports\meek-client

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

C#
public void RefreshTorIdentity()
{
    Socket server = null;
    try
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        server.Connect(ip);
        server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"johnsmith\"" + Environment.NewLine));
        byte[] data = new byte[1024];
        int receivedDataLength = server.Receive(data);
        string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
        server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
        data = new byte[1024];
        receivedDataLength = server.Receive(data);
        stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
        if (!stringData.Contains("250"))
        {
            Console.WriteLine("Unable to signal new user to server.");
            server.Shutdown(SocketShutdown.Both);
            server.Close();
        }
    }
    finally
    {
        server.Close();
    }
}

So Far in the 'Pragmatic Automation with WebDriver' Series

 

If you enjoy my publications, feel free to SUBSCRIBE
Also, hit these share buttons. Thank you!

Source Code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Automate The Planet
Bulgaria Bulgaria
CTO and Co-founder of Automate The Planet Ltd, inventor of BELLATRIX Test Automation Framework, author of "Design Patterns for High-Quality Automated Tests: High-Quality Test Attributes and Best Practices" in C# and Java. Nowadays, he leads a team of passionate engineers helping companies succeed with their test automation. Additionally, he consults companies and leads automated testing trainings, writes books, and gives conference talks. You can find him on LinkedIn every day.

Comments and Discussions

 
QuestionTor failed to start after sometime Pin
zain27-Oct-19 16:50
zain27-Oct-19 16:50 
QuestionRefreshTorIdentity Same IP Pin
Member 1321294220-May-17 10:13
Member 1321294220-May-17 10:13 
QuestionCrash Pin
Member 1110736111-Jan-16 11:50
Member 1110736111-Jan-16 11:50 
AnswerRe: Crash Pin
Member 1110736114-Jan-16 3:35
Member 1110736114-Jan-16 3:35 
GeneralRe: Crash Pin
Anton Angelov14-Jan-16 22:45
Anton Angelov14-Jan-16 22:45 
AnswerRe: Crash Pin
Anton Angelov21-May-17 11:05
Anton Angelov21-May-17 11:05 
QuestionHow to run this code and make exe file Pin
pankajgarg198622-Aug-15 23:27
pankajgarg198622-Aug-15 23:27 
AnswerRe: How to run this code and make exe file Pin
Anton Angelov24-Aug-15 8:11
Anton Angelov24-Aug-15 8:11 
Questionhelp me Pin
4L4K126-Jul-15 2:48
4L4K126-Jul-15 2:48 
AnswerRe: help me Pin
Anton Angelov27-Jul-15 10:05
Anton Angelov27-Jul-15 10:05 
GeneralRe: help me Pin
4L4K128-Jul-15 1:17
4L4K128-Jul-15 1:17 
GeneralRe: help me Pin
Anton Angelov28-Jul-15 2:27
Anton Angelov28-Jul-15 2:27 
GeneralRe: help me Pin
4L4K130-Jul-15 3:06
4L4K130-Jul-15 3:06 
GeneralRe: help me Pin
Anton Angelov30-Jul-15 5:19
Anton Angelov30-Jul-15 5:19 
GeneralRe: help me Pin
Anton Angelov30-Jul-15 3:02
Anton Angelov30-Jul-15 3:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.