Search code examples
c#webrequesttorsocks

New identity for TOR using c#


I'm using my TOR browser to connect to .onion websites and download data using c#. What I wanted to do, was add a button that allowed the user to get a new identity, but nothing I tried have worked so far.

I've tried using telnet, sending a webrequest to the port 9151, running a vbs that was supposed to do this, but nothing worked.

I have tried using TorSharp, but while that worked that only worked Async and I couldN't use that properly. I'm currently using com.LandonKey.SocksWebProxy.

How could I do this?


I'll add relevant code when I know what is needed, just ask.


EDIT:

@Ralph Wiggum

Sadly I can't remember every way I've tried creating a new Identity, as I've said, I tried running a VBS using Diagnostic.Process.Start(), but i doN'T have that script any more.

I also tried using WebRequest but I'm not even sure how that should be done.

This is how that looked as i can remember:

com.LandonKey.SocksWebProxy.Proxy.ProxyConfig pc = new com.LandonKey.SocksWebProxy.Proxy.ProxyConfig();
pc.SocksAddress = IPAddress.Parse(tb_Location.Text);
pc.SocksPort = 9151;
SocksWebProxy sw = new SocksWebProxy(pc);
HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create("http://127.0.0.1");
wreq.Headers.Add("SIGNAL", "AUTHENTICATE \"\"");
wreq.Headers.Add("SIGNAL", "NEWNYM");
using (var wres = wreq.GetResponse())
{
    using (var s = new StreamReader(wres.GetResponseStream()))
    {
        MessageBox.Show(s.ReadToEnd());
    }
}

I also tried using telnet (using PrimS.Telnet), and that didn't work either. That looked something like this:

CancellationToken ct = new CancellationToken(); 
PrimS.Telnet.Client c = new PrimS.Telnet.Client("127.0.0.1", 9151, ct);
c.WriteLine("AUTHENTICATE \"\"\n");
c.WriteLine("SIGNAL NEWNYM"); 

@drew010

As I said, I did use TorSharp but I stopped. It was incredibly easy to create a new identity there, but it ran entirely Async, and I couldn't manage to fix it to use it with the rest of my code.


Solution

  • To get a new identity using through code, you need to open a connection to the control port (usually 9051 and disabled by default [edit your torrc to add ControlPort 9051]) and issue a NEWNYM signal to establish a new circuit.

    To do it you can use the TorControlClient class in TorSharp.

    using Knapcode.TorSharp.Tools.Tor;
    
    TorControlClient tc = new TorControlClient();
    tc.ConnectAsync("localhost", 9051);
    tc.AuthenticateAsync(null); // you should password protect your control connection
    tc.SendCommandAsync("SIGNAL NEWNYM");
    

    You can also use this batch file to request a new identity but C# is probably better for your application. Reference that code to see the sequence on the control connection for getting a new identity.

    See ControlPort and HashedControlPassword configuration options.

    Hope that helps.