Git Product home page Git Product logo

dotnettor's Introduction

DotNetTor

Stable and performant Tor library in .NET Core.

Windows Linux & OSX
Windows build status Linux & OSX build status

See quickstart tutorial on CodeProject

Build & Test

  1. git clone https://github.com/nopara73/DotNetTor
  2. cd DotNetTor/
  3. dotnet restore
  4. cd src/DotNetTor.Tests/
  5. Configure Tor properly.
  6. dotnet test

Configure Tor

  1. Download Tor Expert Bundle: https://www.torproject.org/download/download
  2. Download the torrc config file sample: https://github.com/nopara73/DotNetTor/blob/master/torrc
  3. Place torrc in the proper default location (depending on your OS) and edit it:
  • Optionally uncomment and edit the SocksPort, if you don't uncomment it will default to 9050 port anyway
  • The default ControlPort in the sample is 9051, optionally edit it.
  • Modify the password hash
    • To run my tests, for the ControlPortPassword = "ILoveBitcoin21" the hash should be: HashedControlPassword 16:0978DBAF70EEB5C46063F3F6FD8CBC7A86DF70D2206916C1E2AE29EAF6
    • For your application you should use different one, a more complicated one. Then start tor like this: tor --hash-password password where password is the password you've chosen. It will give you the HashedControlPassword.
  1. Start tor, it will listen to the ports you set in the config file.

Usage

var requestUri = "http://icanhazip.com/";

// 1. Get real IP
using (var httpClient = new HttpClient())
{
	var message = httpClient.GetAsync(requestUri).Result;
	var content = message.Content.ReadAsStringAsync().Result;
	Console.WriteLine($"Your real IP: \t\t{content}");
}

// 2. Get Tor IP
using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", socksPort: 9050)))
{
	var message = httpClient.GetAsync(requestUri).Result;
	var content = message.Content.ReadAsStringAsync().Result;
	Console.WriteLine($"Your Tor IP: \t\t{content}");

	// 3. Change Tor IP
	var controlPortClient = new ControlPort.Client("127.0.0.1", controlPort: 9051, password: "ILoveBitcoin21");
	controlPortClient.ChangeCircuitAsync().Wait();

	// 4. Get changed Tor IP
	message = httpClient.GetAsync(requestUri).Result;
	content = message.Content.ReadAsStringAsync().Result;
	Console.WriteLine($"Your other Tor IP: \t{content}");
}

Acknowledgement

Originally the SocksPort part of this project was a leaned down, modified and .NET Core ported version of the SocketToMe project.
Originally the ControlPort part of this project was a leaned down, modified and .NET Core ported version of the Tor.NET project.
At this point of the development you can still find parts of the former project in the codebase, however the latter has been completely replaced.

dotnettor's People

Contributors

halotron avatar lontivero avatar mikeapple avatar nicolasdorier avatar nopara73 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotnettor's Issues

Help wanted

Hello,
thank you for your lib.

I made it work only partially (not a lib bug).
This part of your code works:

// 2. Get Tor IP
using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", socksPort: 9050)))
{
	var message = httpClient.GetAsync(requestUri).Result;
	var content = message.Content.ReadAsStringAsync().Result;
	Console.WriteLine($"Your Tor IP: \t\t{content}");
}

But this part of code throws me an "AggregateException"

// 3. Change Tor IP
	var controlPortClient = new ControlPort.Client("127.0.0.1", controlPort: 9051, password: "ILoveBitcoin21");
	controlPortClient.ChangeCircuitAsync().Wait();

That's because I don't know where to put torcc file (Windows 10 x64). Your "Place torrc in the proper default location (depending on your OS) and edit it" should be more useful if you specify where "the proper location" is. I searched over internet with no success. Shouldn't it be useful to specify a path for the lib to search for torcc file?

Also, Nuget marks your lib as "Deprecated and no more maintained". I hope it's not true......

Thank you for your help.

Fix Linux/OSX HTTPS, OpenSSL, .NET Core bug

.NET Core behaves differently on Windows and Linux. Maybe wait until it gets fixed?

3de217f

SslStream httpsStream;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
	httpsStream = new SslStream(stream, leaveInnerStreamOpen: true);
else // TODO: Fix this security vulnerability
{
	httpsStream = new SslStream(
		stream,
		leaveInnerStreamOpen: true,
		userCertificateValidationCallback: (a, b, c, d) => true);
}

multithreading?

Is it possible to use DotNetTor in the multithreading application.

Using DotNetTor with TcpClient

Is there any possibility for using DotNetTor with a TcpClient or Socket instead of HttpClient?

I know that HttpClient is much more feature rich than a TcpClient or Socket however I have a situation where I should use TcpClient or Socket instead.

Implement proper exception patterns

My most common mistakes to correct are:

  • DO NOT throw System.Exception.
  • Use Guard everywhere, only throw Argument...Exceptions from Guard.
  • Throw exceptions instead of returning an error code.
  • Use grammatically correct error messages (with proper punctuation)
  • Never test for exception message, they can change.
  • Don't ever swallow exceptions (If needed, log it instead)
  • User predefined exceptions, mostly these: InvalidOperationException, NotSupportedException, FormatException (and the previously mentioned Guard's Argument...Exceptions)
  • When predefined exceptions are not sufficient create own exception

How to set cookie in POST or GET request?

  1. httpClient.DefaultRequestHeaders.Add("Cookie", CookieSID); not work, (the header does not contain cookies in the debugger)
  2. TorSocks5Handler do not support Properties CookieContainer
    Please add the ability to work with cookies using properties in TorSocks5Handler:
  • CookieContainer
  • UseCookies

Support for UTF-8 Post HttpContent

Hi, cool library.
I'm running into an issue when trying to pass non ascii characters in a call.

Simplest way to explain is if you add

            var httpContent = new StringContent("Hello ñ", Encoding.UTF8, "application/json");
            var httpResponse = await httpClient.PostAsync(requestUri, httpContent);

To the end of the RequestWith3IpAsync() method of the Example project.
Removing the ñ works ok but with it it hangs on StreamExtensions.ReadByteAsync() when the call is made to stream.ReadAsync().

I'm running Visual studio for Mac but have just tried it on a Windows VS2017 install and I get the same issue.

Thanks for any help.

How to send GET and POST request in one HttpClient?

How to use(get and set) cookies (CookieContainer or other) in HttpClient and use TOR?
I need:

  1. get cookies and main page content with one request
  2. use received cookies and some data from the content for post-query
using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", socksPort: 9050)))
                {
                    HttpResponseMessage message = httpClient.GetAsync(IndexPage).Result;
                    string content = message.Content.ReadAsStringAsync().Result;
                    var doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(content);
                    var form = doc.DocumentNode.SelectSingleNode("//*[@name='loginFormElement']");
                    LoginAction = form.Attributes["action"].Value;

                    List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("username", "test"),
                        new KeyValuePair<string, string>("password", "test"),
                    };
                    FormUrlEncodedContent PostContent = new FormUrlEncodedContent(pairs);

                    HttpResponseMessage message2 = httpClient.PostAsync(LoginAction, PostContent).Result;
                    string content2 = message2.Content.ReadAsStringAsync().Result;
                }

HttpResponseMessage message2 EXCEPTION

System.AggregateException
HResult=0x80131500
Сообщение = Произошла одна или несколько ошибок.
Источник = mscorlib
Трассировка стека:
в System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
в System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) в System.Threading.Tasks.Task1.get_Result()
в WindowsFormsApp1.AccountChecker.GetAccountInfo2() в C:\Users\fracta4\source\Test4\WindowsFormsApp1\WindowsFormsApp1\AccountChecker.cs:строка 212
в WindowsFormsApp1.AccountChecker.check(Object tuple) в C:\Users\fracta4\source\Test4\WindowsFormsApp1\WindowsFormsApp1\AccountChecker.cs:строка 48
в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart(Object obj)

Внутреннее исключение 1:
TorException: Failed to send the request

Внутреннее исключение 2:
IOException: Не удается прочитать данные из транспортного соединения: Программа на вашем хост-компьютере разорвала установленное подключение.

Внутреннее исключение 3:
SocketException: Программа на вашем хост-компьютере разорвала установленное подключение

в DotNetTor.SocksPort.SocksPortHandler.d__16.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Net.Http.HttpClient.d__58.MoveNext()

Accepting chunked tranfer encoded responses does not work properly

I try to get webpage using code like this

using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", socksPort: 9050)))
{
	var message = httpClient.GetAsync("https://allegro.pl").Result;
	var content = message.Content.ReadAsStringAsync().Result;
	Console.WriteLine($"Allegro tor: \n{content}");
}

In ReadLine() when endPosition > _bufferSize ByteStreamReader goes into infinite while loop. Sometime first call of httpClient.GetAsync is ok, but usually it frezze.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.