HttpWebRequest.Create and firewalls - c#

I need to check whether a given host is replying to HTTP web requests.
So, all I need to do is HttpWebRequest.Create(someURI) and check the response, right?
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(targetUri);
TimeSpan timeOut = TimeSpan.FromSeconds(timeOutInSeconds);
webRequest.Timeout = (int)timeOut.TotalMilliseconds;
webRequest.Proxy = proxy;
webRequest.AllowAutoRedirect = false; // get extra information with this turned off, but doesn't affect the problem
response = webRequest.GetResponse() as HttpWebResponse;
Well, the problem that's come up is that if someURI is blocked by our firewall (e.g. "gibber.com" is blocked), then I get back a valid HttpWebResponse, it doesn't throw, and the ResponseURI property is set to the blocked URI ("gibber.com") even though it's actually our server responding.
Within the HTTP header there will be a Location key and its value is the IP of the local server. But I don't want to parse text to work out if a request actually bounced. What's the correct way to do this?
Thanks

check to see if response.ResponseUri corresponds to the given host or your firewall.

Related

C# - Check if a URI that is within the network is valid

I found this code from here it works for uri like "https://google.com" but it doesn't work for something like "https://172.61.58.168/Account/Login/". I actually don't know why. I have an App using that URI that has an API that I need to call. I can successfully do an api-call and I just decided to make a validation first if the base uri exist and is valid.
Help. Thanks.
code:
bool isHttpValid = false;
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create("https://172.16.85.186/Account/Login/") as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
response.Close();
isHttpValid = true;
}
catch
{
//Any exception will returns false.
isHttpValid = false;
}
First of all you should use HttpClient instead of WebRequest, then you are checking that a HTTP request is valid, however your using a HTTPS URL.
If you want a method that check both HTTP and HTTPS URLs, you have to think how are you going to manage HTTPS certificates, due to that exception:
System.Net.WebException: The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure. ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Maybe you want to add that custom certificate as secure, or you want to remove the security policy that checks the SSL certificates (I don't recommend it), following that other question.
I hope this can help you.

HttpWebRequest Operation Timeout with CookieContainer

When I am using HttpWebRequest and add this:
CookieContainer container = new CookieContainer();
request.CookieContainer = container;
it will throw an Operation Timeout exception in
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
If I don't add the CookieContainer the program runs without errors. Why doesn't this work?
I had this problem too. when I am requesting a Web Page and I put the HttpWebRequest in the Page_Load function and add cookie from current page into CookieContainer but it just hang in there till to timeout
the problem is when I first requesting the web page asp dot net just locked the session for protecting session being writing simultaneously from different place. when I try to call HttpWebRequest to request the same domain same Session it will be block till the first page end it's session lock, meanwhile, the first page is waiting for HttpWebRequest ends it job
the two request just waiting for each other till to timeout.
the good news is I found a way to solve this problem, I just set EnableSessionState="ReadOnly" in the first page, it makes first page that I call do not lock the session.
hope this can help someone.
How are you creating Request object??
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
CookieContainer
Try to set myWebRequest.Timeout =xxx
If you are running multiple concurrent requests try setting connections limit
System.Net.ServicePointManager.DefaultConnectionLimit
ServicePoint.ConnectionLimit
Check these links for more information:
HttpWebRequest "operation has timed out"
I need help setting .NET HttpWebRequest timeout
Adjusting HttpWebRequest Connection Timeout in C#
here are many reasons why GetResponse() might hang. Some are:
1) You have reached the connection limit on the client ( 2 conns per http/1.1 server, 4 connections per http/1.0 server, or custom limit set on the ServicePoint), and no connection is free to send a request to the server. In other words, you might have 2 requests outstanding (eg: to a 1.1 server) which are taking more than 2 minutes to complete, and then issue another GetResponse() to the same server. The last getresponse() might time out.
2) You have not closed the response stream of an earlier httpwebresponse. So, even if a connection is free, the request wont be sent.
3) The server is taking too long to send the response.
Situation 1:
There can be several reasons beind it. I wrote the following lines after reading about your problem and this code works,
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://google.com");
req.Method = "GET";
req.Timeout = 282;
CookieContainer cont = new CookieContainer();
req.CookieContainer = cont;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
Console.Write(reader.ReadToEnd());
}
resp.Close();
req.Abort();
Console.ReadLine();
I wrotereq.Timeout = 282;because i tested for several values and http://google.com does takes 282 milisecond from my computer to respond. From a slower internet connection, this code may return timeout.
Please be sure to set the time out high enough.
Situation 2:
May be the server you are connecting to takes little bit longer if it realize that cookie is enabled. When you don't set anything to req.CookieContainer then cookie is disabled. So please be sure about this fact. :) hope it will work.

C# How to spoof IP address for WebRequest

I have asp.net website hosted and I am making WebRequest to post data and get response. The website is having IP filtering. I want to spoof sender IP address for testing purpose. Is it possible to do it programmatically or I have to use any tool.
public string GetResponse(string request)
{
lock (Obj)
{
request = request + _dataControlInfo.SendEndingWith;
Logger.Info(request);
var req = (HttpWebRequest)WebRequest.Create(_serviceUrl);
req.Headers.Add("SOAPAction", "\"\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
var stm = req.GetRequestStream();
var bytes = UtfEncoding.StringToUtf8ByteArray(request);
stm.Write(bytes, 0, bytes.Length);
stm.Close();
var resp = req.GetResponse();
var stmr = new StreamReader(resp.GetResponseStream());
var strResponseXml = stmr.ReadToEnd();
Logger.Info(strResponseXml);
return strResponseXml;
}
}
Please specify any possibilities.
What your looking for is SharpPCap which is a .NET port of WinPCap.. it allows you to do IP Spoofing, which is what your talking about. The only problem with your idea is that you wont be able to get a response back. You can send requests out, but if you dont have a proper return address then the request will be lost in the interwebs.
Edit
To do this yoruself w/out the help of a library you will need to construct the raw packets yourself. This has been answered here.
If you're expecting to get a response, then no. Without the correct IP address, the server won't send the response to the correct destination.
If you insist on trying anyway, see this article for programmatically setting the client's IP address.
Or you can use Web Performance Tests and a load test with IP Switching enabled
You can try to use a proxy, as documented here.
( http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.proxy.aspx ).
Setting up a proxy on a different computer, then configuring that computer as your requests proxy server should make the request appear as if it came from the proxy's IP, not yours.
Some servers can also consider X-Forwarded-For and X-Real-IP headers.
So if server checks for these headers you can add them to your Web request.
But it depends on server implementation.
Use the Spoof class found in the System.Security namespace...

What domain should I give this cookie?

I'm trying to call a web service from a c# application, with sessionID.
In order to do this I need to set the "Domain" header in a cookie.
In Fiddler it looks like - "ASP.NET_SessionId=izdtd4tbzczsa3nlt5ujrbf5" (no domain is specified in the cookie).
The web service is at - "http://[some ip goes here]:8989/MyAPI.asmx".
I've tried:
http://[ip] ,
http://[ip]:8989 ,
http://[ip]:8989/MyAPI.asmx
All of these cause runtime error.
I've also tried the ip alone (i.e. 100.10.10.10) , which doesn't cause a runtime error, and sets the cookie, but the cookie is never sent when I invoke a web method.
Here's my code for setting the domain:
if (!string.IsNullOrEmpty(currentSessionID))
{
req.CookieContainer=new CookieContainer();
Cookie cookie = new Cookie("ASP.NET_SessionId", currentSessionID);
cookie.Domain = GetCookieUrl(); //<- What should this be?
req.CookieContainer.Add(cookie);
}
So what should the domain be?
Thanks.
I believe it should simply be [ip]. Drop the http:// part of what you've tried.
According to this page on MSDN, your code should be
cookie.Domain = "100.10.10.10";
Next, exactly what error are you getting? Also, are you confusing a Compile error with a Runtime error? I find it hard to believe you are getting a compilation error as Domain is a String property which means you can put pretty much anything into it.
Finally, why are you sending a cookie to a web service? The normal way is to pass everything in the form post or on the query string.
Update
BTW, if you absolutely must add a cookie to the header in order to pass it to a web service, the way you do this is (taken from here):
byte[] buffer = Encoding.ASCII.GetBytes("fareId=123456"); //the data you want to send to the web service
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
WebReq.Headers["Cookie"] = "ASP.NET_SessionId=izdtd4tbzczsa3nlt5ujrbf5"
Stream PostData = WebReq.GetRequestStream();
Note that this sets the header inline with the request without instantiating a "cookie" object. The Domain property of a cookie is to help ensure the cookie is only sent to the domain listed. However, if you are initiating the request and trying to append a cookie to it, then the best way is to just add it as a string to the request headers.
The reason the cookie was not sent is that the request's content length should be set after adding the cookie, and not before.
The domain is the ip alone.
// Simple function to get cookie domain
private string GetCookieDomain(string uri)
{
Uri req_uri = new Uri(uri);
return req_uri.GetComponents(UriComponents.Host, UriFormat.Unescaped);
}

Getting the location from a WebClient on a HTTP 302 Redirect?

I have a URL that returns a HTTP 302 redirect, and I would like to get the URL it redirects to.
The problem is that System.Net.WebClient seems to actually follow it, which is bad. HttpWebRequest seems to do the same.
Is there a way to make a simple HTTP Request and get back the target Location without the WebClient following it?
I'm tempted to do raw socket communication as HTTP is simple enough, but the site uses HTTPS and I don't want to do the Handshaking.
At the end, I don't care which class I use, I just don't want it to follow HTTP 302 Redirects :)
It's pretty easy to do
Let's assume you've created an HttpWebRequest called myRequest
// don't allow redirects, they are allowed by default so we're going to override
myRequest.AllowAutoRedirect = false;
// send the request
HttpWebResponse response = myRequest.GetResponse();
// check the header for a Location value
if( response.Headers["Location"] == null )
{
// null means no redirect
}
else
{
// anything non null means we got a redirect
}
Excuse any compile errors I don't have VS right in front of me, but I've used this in the past to check for redirects.
On HttpWebRequest you can set AllowAutoRedirect to false to handle the redirect yourself.
The HttpWebRequest has a property AllowAutoRedirect which you can set to false (it is always true for WebClient), and then get the Location HTTP header.
Also, for someone who just needs the new location, HttpResponseMessage has a RequestMessage property. Sometimes it can be useful, because WebClient doesn't support changing the AllowAutoRedirect property once it's been set.

Categories

Resources