How to secure my generic handler calls? - asp.net

I am creating a myspace application and for some database entries I am using generic handlers which I have hosted on another website. From my myspace application I use ajax calls to those handlers to perform the activities that I want. I want to know how can I make these ajax calls secure? I mean I want to be sure that the handlers are being called by only the myspace app and not by entering url into the browser etc. Any ideas?

You can secure you Generic Web Handler by doing trick with UrlReferrer for e.g
if (context.Request.UrlReferrer == null)
{
context.Response.Write("Invalid Request");
return;
}
In addition you can check if UrlReferrer != null then domain Name must match with your incoming request url say for e.g.
if(Request.UrlReferrer.ToString().indexOf("http://www.tyamjoli.com")!=-1)
{
//Valid request
}

This is 100% impossible. Everyone will have access to your javascript and can modify it however they want. They can use TamperData to view all requests that the browser makes and drop/modify/replay them.

I don't know much about myspace apps but is there a server component to it? If so, you could first request a "token" from the app which would be the encrypted action and some arbitrary timeout, say 3 seconds. The token is then passed to the generic handler which decrypts it then checks the timeout. If valid, then the decrypted action is performed.
Outside factors such as network latency and un-synchronized clocks could keep some actions from being performed. This should hamper simple replay attacks but is still vulnerable to a scripted attack.

Related

Track a client through HTTP request

In case of HTTP requests like HEAD / GET / POST etc, which information of client is received by the server?
I know some of the info includes client IP, which can be used to block a user in case of, lets say, too many requests.
Another information of use would be user-agent, which is different for browsers, scripts, curl, postman etc. (Of course client can change default by setting request headers, but thats alright)
I want to know which other parameters can be used to identify a client (or define some properties)? Does the server get the mac address somehow?
So, is there a possibility that just by the request, it is identifiable that this request is being done by a "bot" (python or java code, eg.) vs a genuine user?
Assume there is no token or any such secret shared between client-server so there is no session...each subsequent request is independent.
The technique you are describing is generally called fingerprinting - the article covers properties and techniques. Depending on the use there are many criticisms of it, as it bypasses a users intention of being anonymous. In all cases it is a statistical technique - like most analytics.
Putting your domain behind a service like cloudflare might help prevent some of those bots from hitting your server. Other than a service like that, setting up a reCAPTCHA would block bots from accessing any pages behind it.
It would be hard to detect bots using solely HTTP because they can send you whatever headers they want. These services use other techniques to try and detect and filter out the bots, while allowing real users to access the site.
I don't think you can rely on any HTTP request header, because a client might not send it to the server, and/or there might be proxies between the client and the server that strip or alter the request headers.
If you just want to associate a unique ID to an HTTP request, you could generate an ID on your backend. For example, the JavaScript framework Hapi.js computes a request ID using this code:
new Date() + '-' + process.pid + '-' + Math.floor(Math.random() * 0x10000)
You might not even need to generate an ID manually. For example, if your app is on AWS and there is an Application Load Balancer in front of your backend, the incoming request will have the custom header X-Amzn-Trace-Id.
As for distinguishing between requests made by human clients and bots, I think you could adopt a "time trap" approach like the one described in this answer about honeypots for spambots.
HTTP request headers are not a good way to track users that use your site. This is because users can edit these headers and the server has no way to verify their authenticy. Also, in the case of the IP Address, it can change during a session if, for example, a user is on a mobile network.
My suggestion is using a cookie with a unique, random id, given to the user the first time they land on a page of your site. Keep in mind that the user can still edit/remove this cookie, so it isn't a perfect method. If you can force the user to login, then you could track the user with their session token.

Implementing SSE (Server Sent Events) security

I am little new to SSE - server sent events implementation.
What I am trying to do is: to maintain a security check before connecting to SSE urls.
For ex- I have an SSE url which the clients will connect to , through EventSource:
new EventSource("http://my.example.com/deviceData");
So, not every client should be able to connect to it. I have to restrict it to some clients. How can I do that?
A code sample will be really helpful.
If the restriction is by IP, your server-side script can look at the headers and reject based on that. (It could also reject based on any of the other headers, but most of them can be forged, e.g. user-agent.)
If you are after the using logging in, you should use cookies. The simplest way is to have a login form on my.example.com that validates the user, and sends back a cookie. That cookie will then be sent to your SSE script, which can use its contents to validate the user. (If using this approach, you may also want to use https URLs: make sure both the login form and the SSE script are both on https, in that case.)

Call an ASMX webservice in javascript without resetting ASP.NET authentication timers

Quick summary
Pinging back to a webservice in ajax from the client keeps the user's session alive, I don't want this to happen.
More extensive summary
For a website we're developing, we need the client to ping back (in js) to a webservice (ASMX) on the server (IIS7.5). This happens to let the server know that the user is still on the site, and hasn't browsed away to another site.
This is as our customer wants to let users lock records, but if they browse away to other sites, then let other people take over those locked records. Perhaps the distinction between the client being on the site but inactive and on another site seems unimportant, but that's kinda irrelevant, I don't get to write the UI spec, I just have to make it work.
My problem is this, the ping stops the user from being timed out on the server through the standard forms authentication timeout mechanism. Not surprising as there is that 30 second ping in the background keeping the session alive. Even though we want to know if the user is still on the site, we want the normal forms authentication timeout mechanism to be honoured.
I thought I might be able to fix this by removing the ASP.NET_SessionId and .ASPXAUTH cookies in the XMLHttpRequest that is the server ping, but I can't figure out how to do this.
This is how my web service & method are defined:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class PingWS : WebService
{
[WebMethod]
public void SessionActive(string sessionID)
{
// does stuff here
}
This is how I'm calling it in js (request is over HTTPS, :
$.ajax({
type: "POST",
url: "PingWS.asmx/SessionActive",
data: 'sessionID=' + aspSessionID + '}',
beforeSend: function (xhr) {
xhr.setRequestHeader('Cookie', '');
xhr.setRequestHeader('Cookie', 'ASP.NET_SessionId=aaa; .ASPXAUTH=bbb;');
},
dataType: "json"
});
I was trying with the setRequestHeader, but that just appends to the header rather than overwrites the header, and IIS is happy to ignore that junk I added.
I'm thinking maybe I should be trying to do this at the server end, someone take PingWS.asmx out of the loop so that it doesn't keep the session active, but I'm not sure how to do this.
Although the title of the question is focused on clearing the cookie in the header, I'd be super happy if anyone points out that I'm being really stupid and there is actually a much better way of trying to do what I'm doing.
I'm thinking at this stage maybe I need to add something to the webmethod that says how long this particular page has been inactive, and use that knowledge to timeout manually. That actually sounds pretty easy, so I think I'll do that for now. I'm still convinced that there must be an easy way to do what I originally wanted to do though.
Update
I'm thinking I'm pretty screwed in terms of cookie manipulation here as both the .ASPXAUTH and ASP.NETSessionId cookie are HttpOnly, which means the browser takes them out of your hands, you can't access them via the document.cookies object. So I would say that leaves me with:
Updating my SessionAlive webmethod to track each request so I can tell how long the user has been sitting idle on a page and timeout if needs be
Marking the .asmx page somehow on the server end so that it's taken out of the normal authentication/session tracking flow
I know how to do 1. so I'll start there but 2. seems much cleaner to me.
You could restrict the authentication cookie to a given Path:
<authentication mode="Forms">
<forms path="/admin" />
</authentication>
This way the authentication cookie will only be sent to the /admin portion of your site and if you put your web service at the root you can ping it with AJAX without sending the cookie.
Another option is to simply host this webservice into a separate virtual directory.
As you're finding you're out of luck with client cookie manipulation (or clientanipulation of any kind). Manipulating headers might be possible but you'd have to intercept the traffic very early in the pipeline. I don't even know if it will be possible in the service itself but a traffic manager like Zeus could do it. I don't believe it's possible to configure the session engine in such a way as to ignore a given combination of endpoint and client request and although it should be possible to replace the entire session engine that will be undocumented and extremely time consuming I'd think.
Basically you need to manipulate traffic before it touches the service or you're not going to resolve this. Session was not designed to be variant.
There is a server side answer. Basically you disable sliding timeouts on forms authentication, then manually slide the timeout yourself, and skip it for the ping.
Pretty easy for me as every page uses the same root Site.Master and all pages inherit from the same base class.
Summed up here:
http://picometric.blogspot.com/2009/04/manual-sliding-expiration.html

how to save and retrieve cookies using ajax webservice calls

Hi I have web app which stores certain things on a page in a cookie when the page posts back in case the user doesn't finish what they're doing and come back later. But now I must do a javascript time-out and actively save the info to the cookie rather than wait for the user to postback. All my cookie code is on server side where I use Response and Request objects to read and write cookies and I want to leverage that. So I would like to just use ajax calls to a webservice. Is there a way for me to access Request and Response objects and read and write cookies to the browser via those objects during a webservice call? Or should I just go with javascript?
EDIT: Sorry i wanted to specify that I would like to use jquery-ajax.
Implement an ajax callback on a timer that posts back every n number of seconds. When the ajax posts back, check your constraints and simply update the cookie.
OK so I created the static web method on .cs side of the page and in the method I enable session. So this way, I can save stuff to cookie by making ajax calls and using my already existing .cs cookie code.

Response.Redirect and Server.Transfer [duplicate]

What is difference between Server.Transfer and Response.Redirect?
What are advantages and disadvantages of each?
When is one appropriate over the other?
When is one not appropriate?
Response.Redirect simply sends a message (HTTP 302) down to the browser.
Server.Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.
Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
Server.Transfer() does not change the address bar. You cannot hit back.
I use Server.Transfer() when I don't want the user to see where I am going. Sometimes on a "loading" type page.
Otherwise I'll always use Response.Redirect().
To be Short: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.
Something I found and agree with (source):
Server.Transfer is similar in that it sends the user to another page
with a statement such as Server.Transfer("WebForm2.aspx"). However,
the statement has a number of distinct advantages and disadvantages.
Firstly, transferring to another page using Server.Transfer
conserves server resources. Instead of telling the browser to
redirect, it simply changes the "focus" on the Web server and
transfers the request. This means you don't get quite as many HTTP
requests coming through, which therefore eases the pressure on your
Web server and makes your applications run faster.
But watch out: because the "transfer" process can work on only those
sites running on the server; you can't use Server.Transfer to send
the user to an external site. Only Response.Redirect can do that.
Secondly, Server.Transfer maintains the original URL in the browser.
This can really help streamline data entry techniques, although it may
make for confusion when debugging.
That's not all: The Server.Transfer method also has a second
parameter—"preserveForm". If you set this to True, using a statement
such as Server.Transfer("WebForm2.aspx", True), the existing query
string and any form variables will still be available to the page you
are transferring to.
For example, if your WebForm1.aspx has a TextBox control called
TextBox1 and you transferred to WebForm2.aspx with the preserveForm
parameter set to True, you'd be able to retrieve the value of the
original page TextBox control by referencing
Request.Form("TextBox1").
Response.Redirect() should be used when:
we want to redirect the request to some plain HTML pages on our server or to some other web server
we don't care about causing additional roundtrips to the server on each request
we do not need to preserve Query String and Form Variables from the original request
we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)
Server.Transfer() should be used when:
we want to transfer current page request to another .aspx page on the same server
we want to preserve server resources and avoid the unnecessary roundtrips to the server
we want to preserve Query String and Form Variables (optionally)
we don't need to show the real URL where we redirected the request in the users Web Browser
Response.Redirect redirects page to another page after first page arrives to client. So client knows the redirection.
Server.Transfer quits current execution of the page. Client does not know the redirection. It allows you to transfer the query string and form variables.
So it depends to your needs to choose which is better.
"response.redirect" and "server.transfer" helps to transfer user from one page to other page while the page is executing. But the way they do this transfer / redirect is very different.
In case you are visual guy and would like see demonstration rather than theory I would suggest to see the below facebook video which explains the difference in a more demonstrative way.
https://www.facebook.com/photo.php?v=762186150488997
The main difference between them is who does the transfer. In "response.redirect" the transfer is done by the browser while in "server.transfer" it’s done by the server. Let us try to understand this statement in a more detail manner.
In "Server.Transfer" following is the sequence of how transfer happens:-
1.User sends a request to an ASP.NET page. In the below figure the request is sent to "WebForm1" and we would like to navigate to "Webform2".
2.Server starts executing "Webform1" and the life cycle of the page starts. But before the complete life cycle of the page is completed “Server.transfer” happens to "WebForm2".
3."Webform2" page object is created, full page life cycle is executed and output HTML response is then sent to the browser.
While in "Response.Redirect" following is the sequence of events for navigation:-
1.Client (browser) sends a request to a page. In the below figure the request is sent to "WebForm1" and we would like to navigate to "Webform2".
2.Life cycle of "Webform1" starts executing. But in between of the life cycle "Response.Redirect" happens.
3.Now rather than server doing a redirect , he sends a HTTP 302 command to the browser. This command tells the browser that he has to initiate a GET request to "Webform2.aspx" page.
4.Browser interprets the 302 command and sends a GET request for "Webform2.aspx".
In other words "Server.Transfer" is executed by the server while "Response.Redirect" is executed by thr browser. "Response.Redirect" needs to two requests to do a redirect of the page.
So when to use "Server.Transfer" and when to use "Response.Redirect" ?
Use "Server.Transfer" when you want to navigate pages which reside on the same server, use "Response.Redirect" when you want to navigate between pages which resides on different server and domain.
Below is a summary table of which chalks out differences and in which scenario to use.
The beauty of Server.Transfer is what you can do with it:
TextBox myTxt = (TextBox)this.Page.PreviousPage.FindControl("TextBoxID");
You can get anything from your previous page using the above method as long as you use Server.Transfer but not Response.Redirect
In addition to ScarletGarden's comment, you also need to consider the impact of search engines and your redirect. Has this page moved permanently? Temporarily? It makes a difference.
see: Response.Redirect vs. "301 Moved Permanently":
We've all used Response.Redirect at
one time or another. It's the quick
and easy way to get visitors pointed
in the right direction if they somehow
end up in the wrong place. But did you
know that Response.Redirect sends an
HTTP response status code of "302
Found" when you might really want to
send "301 Moved Permanently"?
The distinction seems small, but in
certain cases it can actually make a
big difference. For example, if you
use a "301 Moved Permanently" response
code, most search engines will remove
the outdated link from their index and
replace it with the new one. If you
use "302 Found", they'll continue
returning to the old page...
There are many differences as specified above. Apart from above all, there is one more difference. Response.Redirect() can be used to redirect user to any page which is not part of the application but Server.Transfer() can only be used to redirect user within the application.
//This will work.
Response.Redirect("http://www.google.com");
//This will not work.
Server.Transfer("http://www.google.com");
Transfer is entirely server-side. Client address bar stays constant. Some complexity about the transfer of context between requests. Flushing and restarting page handlers can be expensive so do your transfer early in the pipeline e.g. in an HttpModule during BeginRequest. Read the MSDN docs carefully, and test and understand the new values of HttpContext.Request - especially in Postback scenarios. We usually use Server.Transfer for error scenarios.
Redirect terminates the request with a 302 status and client-side roundtrip response with and internally eats an exception (minor server perf hit - depends how many you do a day) Client then navigates to new address. Browser address bar & history updates etc. Client pays the cost of an extra roundtrip - cost varies depending on latency. In our business we redirect a lot we wrote our own module to avoid the exception cost.
Response.Redirect is more costly since it adds an extra trip to the server to figure out where to go.
Server.Transfer is more efficient however it can be a little mis-leading to the user since the Url doesn't physically change.
In my experience, the difference in performance has not been significant enough to use the latter approach
Server.Transfer doesn't change the URL in the client browser, so effectively the browser does not know you changed to another server-side handler. Response.Redirect tells the browser to move to a different page, so the url in the titlebar changes.
Server.Transfer is slightly faster since it avoids one roundtrip to the server, but the non-change of url may be either good or bad for you, depending on what you're trying to do.
Response.Redirect: tells the browser that the requested page can be found at a new location. The browser then initiates another request to the new page loading its contents in the browser. This results in two requests by the browser.
Server.Transfer: It transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content.
The benefit of this approach is one less round trip to the server from the client browser. Also, any posted form variables and query string parameters are available to the second page as well.
Just more details about Transfer(), it's actually is Server.Execute() + Response.End(), its source code is below (from Mono/.net 4.0):
public void Transfer (string path, bool preserveForm)
{
this.Execute (path, null, preserveForm, true);
this.context.Response.End ();
}
and for Execute(), what it is to run is the handler of the given path, see
ASP.NET does not verify that the current user is authorized to view the resource delivered by the Execute method. Although the ASP.NET authorization and authentication logic runs before the original resource handler is called, ASP.NET directly calls the handler indicated by the Execute method and does not rerun authentication and authorization logic for the new resource. If your application's security policy requires clients to have appropriate authorization to access the resource, the application should force reauthorization or provide a custom access-control mechanism.
You can force reauthorization by using the Redirect method instead of the Execute method. Redirect performs a client-side redirect in which the browser requests the new resource. Because this redirect is a new request entering the system, it is subjected to all the authentication and authorization logic of both Internet Information Services (IIS) and ASP.NET security policy.
-from MSDN
Response.Redirect involves an extra round trip and updates the address bar.
Server.Transfer does not cause the address bar to change, the server responds to the request with content from another page
e.g.
Response.Redirect:-
On the client the browser requests a page http://InitiallyRequestedPage.aspx
On the server responds to the request with 302 passing the redirect address http://AnotherPage.aspx.
On the client the browser makes a second request to the address http://AnotherPage.aspx.
On the server responds with content from http://AnotherPage.aspx
Server.Transfer:-
On the client browser requests a page http://InitiallyRequestedPage.aspx
On the server Server.Transfer to http://AnotherPage.aspx
On the server the response is made to the request for http://InitiallyRequestedPage.aspx passing back content from http://AnotherPage.aspx
Response.Redirect
Pros:-
RESTful - It changes the address bar, the address can be used to record changes of state inbetween requests.
Cons:-
Slow - There is an extra round-trip between the client and server. This can be expensive when there is substantial latency between the client and the server.
Server.Transfer
Pros:-
Quick.
Cons:-
State lost - If you're using Server.Transfer to change the state of the application in response to post backs, if the page is then reloaded that state will be lost, as the address bar will be the same as it was on the first request.
Response.Redirect
Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
It redirects the request to some plain HTML pages on our server or to some other web server.
It causes additional roundtrips to the server on each request.
It doesn’t preserve Query String and Form Variables from the original request.
It enables to see the new redirected URL where it is redirected in the browser (and be able to bookmark it if it’s necessary).
Response. Redirect simply sends a message down to the (HTTP 302) browser.
Server.Transfer
Server.Transfer() does not change the address bar, we cannot hit back.One should use Server.Transfer() when he/she doesn’t want the user to see where he is going. Sometime on a "loading" type page.
It transfers current page request to another .aspx page on the same server.
It preserves server resources and avoids the unnecessary roundtrips to the server.
It preserves Query String and Form Variables (optionally).
It doesn’t show the real URL where it redirects the request in the users Web Browser.
Server.Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.

Resources