Grapevine Remote Connection Bad Request - Invalid Hostname - c#

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();
}

Related

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!!

DotNetTor Cannot Make Requests

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.

Get client IP in Azure through MVC 5 controller

I can't find a question or post specific to Azure for this, and I'm not sure what's different in the environment in Azure versus my testing environments that would cause this.
I've tried a few methods to get this to work but I'm not coming right. Please note this isn't Webapi, so using the HttpRequestMessage, as far as I know, is not going to work either.
Here's what I've tried so far:
Method 1:
string ipAddress = "";
IPHostEntry Host = default(IPHostEntry);
Host = Dns.GetHostEntry(System.Environment.MachineName);
ipAddress = Host.AddressList.SingleOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).MapToIPv4().ToString();
Method 2:
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(userIP))
{
userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;
Thanks in advance.
Read the value transported in this header:
x-forwarded-for: "91.23.44.24:52623"
Note there's a source port number trailing the IP address, so parse accordingly.
Also, as #NicoD correctly points out, the header in question may contain an array of proxy servers the request traversed. For example:
x-forwarded-for: "91.23.44.24:52623, 91.23.44.155"
Syntax
X-Forwarded-For: <client>, <proxy1>, <proxy2>
<client> The client IP address
<proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of the most recent proxy and the left-most IP address is the IP address of the originating client.
What about that glaring port number you ask?
From https://www.rfc-editor.org/rfc/rfc7239:
5.2. Forwarded For
[...] this parameter MAY instead contain an IP
address (and, potentially, a port number).
All client requests are terminated in the frontend layer and proxied via Application Request Routing to your web worker (hosting the MVC5 application).

SFTP connectivity DNS issue - System.Net.Sockets.SocketException: The requested name is valid, but no data of the requested type was found

I am trying to connect to ftp via SharpSSH as below:
Sftp Connection = new Sftp(ftpAddress, FTPLogin, FTPPasword);
Connection.Connect();
Which results in JSchException:
System.Net.Sockets.SocketException: The requested name is valid, but no data of the requested type was found
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostByName(String hostName)
at Tamir.SharpSsh.java.net.Socket..ctor(String host, Int32 port)
at Tamir.SharpSsh.jsch.Util.createSocket(String host, Int32 port, Int32 timeout)
After some search I tried this code:
IPHostEntry ip = Dns.GetHostEntry(ftpAddress);
And I got SocketException: {No such host is known}
Now some background - I am able to connect with Filezilla to ftpAdress with via hostname and IP address (both external and internal).
When I >ping ftp.mydomain.com
I get >10.5.165.15
But on >ping -a 10.5.165.15
I get >ftpnew.mydomain.com
If I am right, I am being rejected because of DNS <> revDNS problem.
My question is - what can I do to actually have my sftp connection work.
Solution was found by checking every possibility and this is how I menaged to establish connection:
First my ftpAddress was set to extrernal/internal IP.
IPHostEntry ip = Dns.GetHostByName(ftpAddress);
Sftp Connection = new Sftp(ip.ToString(),FTPLogin,FTPPassword);
Connection.Connect()
It seems my error was not about DNS<>revDNS but rather due to extra '\' signs in host adress I was trying to call.
Enter only the ip address for the host.
For example
Wrong : "sftp//10.11.12.13" this will result in error
Correct: "10.11.12.13" this is ok
I was facing the same problem now i found the solution for this.
Use following type ftpAddress(URL):
sftp.abcdefg.com with 22 port no. and rest will be same.
Do not use any kind of forward slash "/" and backslash "\" at the end or starting of URL.
I was facing the same problem with this URL = sftp.abcdefg.com/
mine works when I re-arranged the name and address a little bit. Get rid of sftp:// in the beginning of the host name. and , add back 22 port in the parameters.
using X = Renci.SshNet;
ConnectionInfo = new X.ConnectionInfo(_host, 22, _usr,
new X.AuthenticationMethod[] {
new X.PasswordAuthenticationMethod (_usr, _pwd)
}); //_host = yourfavoritesite.whatever.com -- take out sftp://
SftpClient = new X.SftpClient(ConnectionInfo);
SftpClient.Connect();
Another source of this error is if there is a white-space at the beginning of the server name e.g.:
<add key="SftpHost" value=" sftp.whatever.com" />

Failed to resolve IP

Try as I might, I'm unable to resolve an address to IP. The code snippet is shown below. I keep getting the No such host is known exception, even though I could access google with my browser (The DNS server is almost certainly working). I'm however behind company's firewall.
try
{
foreach (IPAddress address in Dns.GetHostAddresses("www.google.com"))
{
Console.WriteLine(address.ToString());
}
}
catch (SocketException e)
{
Console.WriteLine("Source : " + e.Source); // System
Console.WriteLine("Message : " + e.Message); // No such host is known
}
There is nothing wrong with your code. Given that you can access www.google.com from a web browser the next most likely problem is that the web browser is using a proxy server. The web browser is actually accessing www.google.com through the proxy server which is allowed through the firewall. The simple application you wrote is not allowed through the firewall and is resulting in an exception.
You can verify this by looking at the proxy settings in Internet Explorer.
Tools -> Options -> Connections -> Lan Settings
There will be a proxy server group of settings. If there is a value present, this is almost certainly your problem.
You need to set up the proxy:
here's a snippet that should set it up for all the following calls:
protected void SetupProxy(string proxyUrl, string proxyLogin, string proxyPassword, string[] proxyBypass)
{
WebProxy proxy = new WebProxy(proxyUrl);
proxy.Credentials = new NetworkCredential(proxyLogin, proxyPassword);
proxy.BypassList = proxyBypass;
proxy.BypassProxyOnLocal = true;
WebRequest.DefaultWebProxy = proxy;
}
Rather than try through a browser, try pinging www.google.com (or some other host, of course) from the command line.
The ping itself may well not work, but it should show the IP address resolution first. If you get an error message like this:
Ping request could not find host www.google.com.
Please check the name and try again.
then it's likely that the proxy server is doing the DNS lookup for you when you're browsing, and your DNS server is either not working or your machine's network settings are incorrect.

Categories

Resources