DotNetTor Cannot Make Requests - c#

Recently I want to get a .json content from an onion site
(e.g. http://takedownmi4lfjhv.onion/root.json, this is an existing link)
So I installed the C# library DotNetTor (Nuget package is here)
I copy & pasted the DotNetTor QuickStart Example Project sample code and ran it with my C# project.
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; // GOT ERROR HERE // GOT ERROR HERE
var content = message.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Your TOR IP: \t\t{content}");
// 3. Change TOR IP
var controlPortClient = new DotNetTor.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}");
}
However, at the line I marked // GOT ERROR HERE, it poped up an error
System.AggregateException
Inner Exception 1:
TorException: Failed to send the request
Inner Exception 2:
SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:9050
Why failed to send the request? How to resolve that?

The code above is simply a Socks Proxy handler and does not really contain anything about Tor.
new SocksPortHandler("127.0.0.1", socksPort: 9050)
See this link of code. This is nothing more than connecting via a SocksPortHandler 127.0.0.1:9050
But this port is not yet configured to Tor at all.
So before this, you should configure the port.
You can download the Tor Expert Bundle from here. This can help you configure that port for Tor.

Related

How to make GrpcChannel use HTTP/2 on MonoAndroid?

I am trying to make request to my server by MagicOnion protocol (it uses transport from gRPC, but deffrent serialization protocol, message pack instead of protobuf).
An simple test client app, working under net5.0 is executing code like this:
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var address = $"http://{ServerUrl.Host}:5002";
using var channel = GrpcChannel.ForAddress(address);
var myServiceClient = MagicOnionClient.Create<IMyService>(channel);
var result = await myServiceClient.GetMyData();
...and recieves response succesfully. But if I try to execute the same code on Android app, I am seeing this exception message on server logs:
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2ConnectionErrorException: HTTP/2 connection error (PROTOCOL_ERROR): Invalid HTTP/2 connection preface.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ParsePreface(ReadOnlySequence`1& buffer, SequencePosition& consumed, SequencePosition& examined)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.TryReadPrefaceAsync()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
With logs and traffic dump I can see that the client on .Net 5 uses HTTP/2, but on Android - HTTP/1.1. As I can see, this is the only deifference between requests.
So, how can I make Android (API30, monoandroid10.0) client use HTTP/2?
The resolution is to use another gRPCC implementation lib - Grpc.Core. It provides GrpcChannel class wich is compatible with MagicOnion.
In my case, the library didn't work immediately, throwing the error about libgrpc_csharp_ext loading trouble. To solve this, you also have to add pacakge Grpc.Core.Xamarin.
The usage example:
var channel = new Grpc.Core.Channel(ServerUrl.Host, 5002, Grpc.Core.ChannelCredentials.Insecure);
var myServiceClient = MagicOnionClient.Create<IMyService>(channel);
var result = await myServiceClient.GetMyData();

How to detect a connection closure in Kestrel

Once again, the Microsoft documentation leaves me wanting. I am trying to find the correct API where I can configure a callback to trap when a client closes their connection.
When I fire up a gRPC server, in the console I see all of the Kestrel configuration and startup log messages. When I fire up the gRPC client I can see in the server's console log messages indicating a connection has been made as follows:
dbug: Microsoft.AspNetCore.Server.Kestrel.Connections[39]
Connection id "0HMCEE5LHGSKR" accepted.
dbug: Microsoft.AspNetCore.Server.Kestrel.Connections[1]
Connection id "0HMCEE5LHGSKR" started.
When I close the client by clicking the Close Window button (X), I see the following:
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[19]
Connection id "0HMCEE5LHGSKR" reset.
dbug: Microsoft.AspNetCore.Server.Kestrel.Http2[48]
Connection id "0HMCEE5LHGSKR" is closed. The last processed stream ID was 1.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[7]
Connection id "0HMCEE5LHGSKR" sending FIN because: "The client closed the connection."
dbug: Microsoft.AspNetCore.Server.Kestrel.Connections[2]
Connection id "0HMCEE5LHGSKR" stopped.
The option to use the ListenOptions.UseConnectionLogging(ListenOptions) extension method provides no callback option that I can find. Obviously, in the default middleware, the event is being captured, but I cannot find the path to that option. An examination of Microsoft.AspNetCore.Server.Kestrel namespace shows no way (that I can find) how to get to Microsoft.AspNetCore.Server.Kestrel.Connections or Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets data.
I am using Visual Studio 2022, .NET 6, C# 10 and gRPC. Here is my current Kestrel configuration:
// Configure Kestrel, the .NET Core web server.
var hostBuilder = webHostBuilder.ConfigureKestrel (kestrelServerOptions => {
kestrelServerOptions.ConfigureHttpsDefaults (httpsConnectionAdapterOptions => httpsConnectionAdapterOptions.SslProtocols = SslProtocols.Tls12);
// Read in the X.509 certificate file.
var certPath = Path.Combine (builder.Environment.ContentRootPath, "Certs", $"{environment}.pfx");
kestrelServerOptions.ConfigureEndpointDefaults (listenOptions => {
_ = listenOptions.UseHttps (certPath, password);
logger.Debug ($"Using {certPath} as the cert file.");
logger.Debug ("Configuring host to use HTTP/2 protocol.");
listenOptions.Protocols = HttpProtocols.Http2;
});
logger.Debug ("Reading config values for the server name and port.");
// Get the host name and port number to bind the service to.
var port = builder.Configuration.GetValue<int> ("AppSettings:OperationsServerPort");
var address = IPAddress.Parse ("0.0.0.0");
if (address != null) {
logger.Debug ($"Host will listen at https://{address}:{port}");
kestrelServerOptions.Listen (address, port);
} else {
logger.Error ("DNS address for service host cannot be determined! Exiting...");
Environment.Exit (-1);
}
});
Any clues, guidance, examples will be greatly appreciated!
Well, I may be late to the game in understanding all of this ASP.NET Core configuration, but to trap connections coming and going is tooooooo simple... Adding a middleware delegate to the listener is all it took...
var ipEndpoint = new IPEndPoint (address, port);
kestrelServerOptions.Listen (ipEndpoint, action => action.Use (async (context, next) => {
Console.WriteLine ($"INTERNAL ---------------- New Connection: {context.ConnectionId}");
await next.Invoke ();
Console.WriteLine ($"INTERNAL ---------------- Connection terminated: {context.ConnectionId}");
}));
This snippet modified my original post above by adding the middleware delegate. The required reading that got me beyond the logjam can be found here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0
I hope this helps somebody!!

Grapevine Remote Connection Bad Request - Invalid Hostname

I set up a rest service with the grapevine, plus I'm having trouble accessing remotely even with the firewall turned off.
Are you only accepting connections through localhost or 127.0.0.1, when I try to access the IP of the machine or remotely gives this error
Bad Request - Invalid Hostname
HTTP Error 400. The request hostname is invalid.
using (var server = new RestServer())
{
server.Port = "9999";
server.LogToConsole().Start();
Console.ReadLine();
server.Stop();
}
Edit: Please refer to the (updated) documentation, specifically the page On Using HttpListener
The current default value is localhost. You can change the directly using the Host property:
server.Host = "*";
Use "*" to indicate that the HttpListener accepts requests sent to the port if the requested URI does not match any other prefix. Similarly, to specify that the HttpListener accepts all requests sent to a port, replace the host element with the "+" character.
So, for Grapevine 4, you could write your code as follows:
using (var server = new RestServer{Port = "9999", Host = "*"})
{
server.LogToConsole().Start();
Console.ReadLine();
server.Stop();
}

Client Certificates in Dotnet Core on Ubuntu

all - I've written a dotnet core API set that functions perfectly on windows. On Ubuntu 14.04, everything works except for one SOAP request to a vendor that uses a client certificate for authentication.
The request always times out. A Netstat trace shows that only 1 byte of data was sent to the remote service on 443. No communication happens for 100 seconds and then the app throws a timeout exception.
I've tried using openssl to export PEM and CRT files and referenced those in addition to the way the code is configured now (pfx w/ password). I've also loaded the certificate portions of the PFX into ca-certs.
Here's the code:
var binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var baseAddress = new Uri(mySettings.ClientUrl);
factory = new ChannelFactory<SingleSignOnSoap>(binding, new EndpointAddress(baseAddress));
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
{
//windows file location
factory.Credentials.ClientCertificate.Certificate = new X509Certificate2(mySettings.PrivateKeyWindowsPath, mySettings.PfxPass);
}
else
{
//linux file location
factory.Credentials.ClientCertificate.Certificate = new X509Certificate2(mySettings.ClientPrivateKeyUnixPath, mySettings.PfxPass);
}
serviceProxy = factory.CreateChannel();
RequestTicketRequest request = new RequestTicketRequest();
RequestTicketRequestBody requestBody = new RequestTicketRequestBody(xmlRequest);
request.Body = requestBody;
RequestTicketResponse response = serviceProxy.RequestTicket(request);
return response.Body.RequestTicketResult;
Wireshark and Tshark show the authentication is actually working ok. The timeout is happening because the ServiceFactory is waiting to receive the response, but the network has sent a connection reset flag ([RST, ACK]) to the remote server. I've been able to reproduce on multiple linux distros so I'm adding an issue to the dotnet core WCF team's queue on github.

Getting Exception from HRESULT: 0x80072F0D when posting to a service in Windows phone 8.1

When I am trying to post a data to an API using HttpClient in Windows Phone 8.1, I am always getting Exception from HRESULT: 0x80072F0D exception. In fiddler, it works fine.
try
{
var requestbody="json data"
HttpClient httpClient = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), new Uri(addressUri));
msg.Content = new HttpStringContent(requestbody);
msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
HttpResponseMessage response = await httpClient.SendRequestAsync(msg).AsTask();
}
catch (Exception ex)
{
getting **Exception from HRESULT: 0x80072F0D**
}
Please tell me what went wrong?
---FYI----
For getting additional information about the HRESULT code : Follow this WebErrorStatus enumeration
var exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult);
if (exceptionDetail == WebErrorStatus.HostNameNotResolved)
{
//
}
This looks like a certificate related problem. Maybe you are using SSL. While lots of programs gracefully override missing certificates if not explicitly necessary (e.g.: browsers) the HttpClient is pretty sensitive against that.
You should try to download the certificate for the connection you're using and store the cert file in your assets folder. When your app starts, push it into the certificate store. This is a snippet I am using in one of my apps. Maybe this makes your exception go away.
Read more here: http://blogs.msdn.com/b/wsdevsol/archive/2014/06/05/including-self-signed-certificates-with-your-windows-runtime-based-windows-phone-8-1-apps.aspx
// Add our custom certificate
try
{
// Read the contents of the Certificate file
System.Uri certificateFile = new System.Uri("ms-appx:///Assets/ca.cer");
Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(certificateFile);
Windows.Storage.Streams.IBuffer certBlob = await Windows.Storage.FileIO.ReadBufferAsync(file);
// Create an instance of the Certificate class using the retrieved certificate blob contents
Windows.Security.Cryptography.Certificates.Certificate rootCert = new Windows.Security.Cryptography.Certificates.Certificate(certBlob);
// Get access to the TrustedRootCertificationAuthorities for your own app (not the system one)
Windows.Security.Cryptography.Certificates.CertificateStore trustedStore = Windows.Security.Cryptography.Certificates.CertificateStores.TrustedRootCertificationAuthorities;
// Add the certificate to the TrustedRootCertificationAuthorities store for your app
trustedStore.Add(rootCert);
}
catch (Exception oEx)
{
// Catch that exception. We don't really have a choice here..
var msg = oEx.Message;
}
You might be able to bypass the error with this code:
var baseFilter = new HttpBaseProtocolFilter();
baseFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidCertificateAuthorityPolicy);
var httpClient = new HttpClient(baseFilter);
This merely silences the error rather than solving the problem, though. I'm not too knowledgeable with SSL errors, and this may not be a safe option, and may not pass app certification. According to the docs:
SSL server certificate errors should only be ignored in advanced scenarios. Disregarding server certificate errors classified as either Ignorable or Fatal may result in the loss of privacy or integrity of the content passed over the SSL session.
Received the same Error as originator. I do not use a proxy.
This worked for me. netsh winhttp reset proxy
Next Fax transmitted without error.
Experienced the 0x80072efd problem. Has cost me hours if not days to solve. The solution that gave instant resolution is the following command from a admin command prompt:
netsh winhttp reset proxy

Categories

Resources