How to does the token prevent csrf attack? - javascript

I have read about CSRF and how the Unpredictable Synchronizer Token Pattern is used to prevent it. I didn't quite understand how it works.
Let's take this scenario :
A user is logged into a site with this form:
<form action="changePassword" method="POST">
<input type="text" name="password"><br>
<input type="hidden" name="token" value='asdjkldssdk22332nkadjf' >
</form>
The server also stores the token in the session. When the request is sent it compares the token in the form data to the token in the session.
How does that prevent CSRF when the hacker can write JavaScript code that will:
Send a GET request to the site
Receive html text containing the request form.
Search the html text for the CSRF token.
Make the malicious request using that token.
Am missing something?

The attacker can't use JavaScript to read the token from the site, because it would be a cross-origin request and access to the data from it is blocked (by default) by the Same Origin Policy (MDN, W3C).
Take this for example:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://google.com");
xhr.addEventListener('load', function (ev) {
console.log(this.responseText);
});
xhr.send();
The JS console reports:
XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource.

It's important to realize that CSRF attacks only happen in the browser. The user's session with the target server is used by the malicious server to forge requests. So how does #1 happen? Two options: you could make the #1 request from the malicious server, but that would simply return a CSRF token for the server's session, or you could make the #1 request using AJAX which, as you correctly identified, would return the CSRF token of the victim user.
Browsers have implemented HTTP access control for this very reason. You must use the Access-Control-Allow-Origin header to restrict which domains may make AJAX requests to your server. In other words your server will ensure the browser doesn't let the malicious site do #1. Unfortunately the documents I've read on the matter aren't very clear about it, but I think that's because servers by default do not send an Access-Control-Allow-Origin header unless configured to do so. If you do need to allow AJAX requests, you must either trust any origins in the header not to perform a CSRF attack, you can selectively lock down sensitive portions of your application to not allow AJAX requests, or use the other Access-Control-* headers to protect yourself.
Using a Synchronizer Token is one way that an application can rely
upon the Same-Origin Policy to prevent CSRF by maintaining a secret
token to authenticate requests
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
You should read up on Cross-Origin Resource Sharing (CORS).

Related

Basic authentication with header - Javascript XMLHttpRequest

I am trying to access Adyen test API that requires basic authentication credentials. https://docs.adyen.com/developers/ecommerce-integration
My credentials work when accessing the API page through browser.
But I get an 401 Unauthorized response when trying to access the API with XMLHttpRequest POST request.
Javascript Code
var url = "https://pal-test.adyen.com/pal/servlet/Payment/v25/authorise";
var username = "ws#Company.CompanyName";
var password = "J}5fJ6+?e6&lh/Zb0>r5y2W5t";
var base64Credentials = btoa(username+":"+password);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic " + base64Credentials);
var requestParams = XXXXXXXX;
xhttp.send(requestParams);
Result
That screenshot shows “Request Method: OPTIONS”, which indicates the details displayed are for a CORS preflight OPTIONS request automatically made by your browser—not for your POST.
Your browser doesn’t (and can’t) send the Authorization header when it makes that OPTIONS request, and that causes the preflight to fail, so the browser never moves on to trying your POST.
As long as https://pal-test.adyen.com/pal/servlet/Payment/v25/authorise requires authentication for OPTIONS requests, there’s no way you can make a successful POST to it.
The reason is because what’s happening here is this:
Your code tells your browser it wants to send a request with the Authorization header.
Your browser says, OK, requests with the Authorization header require me to do a CORS preflight OPTIONS to make sure the server allows requests with that header.
Your browser sends the OPTIONS request to the server without the Authorization header—because the whole purpose of the OPTIONS check is to see if it’s OK to send that.
That server sees the OPTIONS request but instead of responding to it in a way that indicates it allows Authorization in requests, it rejects it with a 401 since it lacks that header.
Your browser expects a 200 or 204 response for the CORS preflight but instead gets that 401 response. So your browser stops right there and never tries the POST request from your code.
The PAL is a Payment Authorisation API. You never want to call it from a browser. You only want to expose your username and password to send in payments in your backend code.
In Client-side encryption, the encryption is done in the browser. You then send the encrypted data to your own server. On your server you then create a payment authorization request (of which the encrypted data is one of the elements, along side payment amount, etc).
If you would be able to manage to make this run from your browser, your end solution will allow your shoppers to change amounts, currency's, payment meta data etc from the JavaScript layer. This should never be the case.
The authorization is for that reason part of the "Server side" integration part of documentation: https://docs.adyen.com/developers/ecommerce-integration?ecommerce=ecommerce-integration#serverside
Depending on your server side landscape the CURL implementation in your favorite language differs, but most of the time are easy to find.
Kind regards,
Arnoud

How to store Access token value in javascript cookie and pass that token to Header using AJAX call

I have a login form, as shown below:
<form method="post" name="logForm" onsubmit="onLogin()" action="dashbooard.html">
<label>Email</label>
<input type="text" name="email">
<label>Password</label>
<input type="password" name="pass">
<input type="submit" name="submit" value="Login" >
</form>
Now when I click on the Login button, I am authenticated by the server and an access_token is generated and returned back to me via a REST API.
I would like to store that access_token in a cookie and pass that token into a request. But, I don't know how to do this. I would love to receive help on this.
Here is how you can use a cookie for your question regarding the access_token:
1. Storing the cookie on the client:
document.cookie='access_token=[value]' where [value] is the token value.
If we use a reader/writer library that MDN provides here, we can do the above as:
docCookies.setItem('access_token', [value]);
The reason why we would use something like this instead of the standard way is to make it easier to access and delete the token, as demonstrated in #3 below.
2. Passing the cookie back to the server:
We need to send the access_token back to the server through the header.
This should automatically be done for you, assuming that the server sends a response after authentication like Set-Cookie: access_token=[value].
If for any reason you encounter an issue regarding Access-Control-Allow-Origin, here is an example of how you can set Access-Control response headers for CORS:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
3. Deleting the cookie:
Using the reader/writer library linked in #1, we can do the following:
docCookies.removeItem('acccess_token');
Security considerations when using cookies for authorization:
XSS, MITM, and CSRF attack vectors should be considered when using cookies for authorization. On a basic level:
For XSS attacks, we can set the HttpOnly flag in the response header by the server to prevent a client side script from accessing the cookie.
For MITM attacks, we can use the Secure flag to guarantee the cookie is not sent over an unencrypted HTTP channel.
For CSRF attacks, the recommendation by OWASP is the Synchronizer Token Pattern. It's basically a randomly generated token that is sent by the server and is sent back by the client to verify a request submission done by the user.
Try this code
document.cookie="username=John Doe";
A more elaborated answer based on above answers, in the success part of your Ajax call.
success: function (json) {
// console.log(json); // log the returned json to the console
var access_token = json.token;
document.cookie="access_token="+access_token;
},

How does angularjs handle csrf?

I am having a bit trouble understanding the following code
run.$inject = ['$http'];
function run($http) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken';
$http.defaults.xsrfCookieName = 'csrftoken';
}
as I always thought that csrf is injected into html forms or ajax calls and not cookie, since csrf is a protection against any adversary trying to use your cookie for authentication.
Can someone give a detail explanation on how angular is handling csrf and how does it get the token from the backend?
I can't answer this better than the angular docs themselves do, so I'll just quote:
Cross Site Request Forgery (XSRF) Protection
XSRF is a technique by which an unauthorized site can gain your user's private data.
Angular provides a mechanism to counter XSRF. When performing XHR
requests, the $http service reads a token from a cookie (by default,
XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only
JavaScript that runs on your domain could read the cookie, your server
can be assured that the XHR came from JavaScript running on your
domain. The header will not be set for cross-domain requests.
To take advantage of this, your server needs to set a token in a
JavaScript readable session cookie called XSRF-TOKEN on the first HTTP
GET request. On subsequent XHR requests the server can verify that the
cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that
only JavaScript running on your domain could have sent the request.
The token must be unique for each user and must be verifiable by the
server (to prevent the JavaScript from making up its own tokens). We
recommend that the token is a digest of your site's authentication
cookie with a salt for added security.
The name of the headers can be specified using the xsrfHeaderName and
xsrfCookieName properties of either $httpProvider.defaults at
config-time, $http.defaults at run-time, or the per-request config
object.
The $http.defaults.xsrfCookieName is just allowing you to specify what the name of the cookie is, otherwise it's going to look for the default XSRF-TOKEN.
On the server side implementation, I'd recommend using some node.js middleware to handle the setting of the initial cookie instead of rolling your own. Take a look at csurf in particular as it seems to be the most popular. You could also try senchalab's csrf middleware. Either of those ought to be enough to get you started.

Cross Origin Resource Sharing (CORS) and Javascript

As an example case let's take this url: http://api.duckduckgo.com/?q=computer&format=json (CORS not enabled on this server!)
We can access the contents from this URL from any popular browser as a normal URL, browser has no issues opening this URL nor the server returns any error.
A server-side language like PHP/RoR can fetch the contents from this URL without adding any additional headers or special server settings. I used following PHP code and it simply worked.
$url='http://api.duckduckgo.com/?q=computer&format=json';
$json = file_get_contents($url);
echo $json;
I just started working in javascript framework, AngularJS. I used following code...
delete $http.defaults.headers.common['X-Requested-With'];
var url="http://api.duckduckgo.com/?q=computer&format=json";
$http.get(url)
.success(function(data) {
$scope.results=data;
})
With above AngularJS code, I received following error:
XMLHttpRequest cannot load http://api.duckduckgo.com/?q=computer&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
AngularJS uses JQuery so I tried the same in JQuery with following code:
var url="http://api.duckduckgo.com/?q=computer&format=json";
$.getJSON(url , function( data ) {
console.log(data);
});
This also produced the same error as did AngularJS code.
Then my further research brought me to the point that it's actually not specific to JQuery and AngularJS. Both of these inherit this issue from Javascript!
Here is an excellent resource with explanation of what CORS is and how to handle with it: http://enable-cors.org/index.html.
And also W3C has it official CORS specification: http://www.w3.org/TR/cors/
So my question is not what CORS is. My question is
My understanding is that whether it is a web browser or it is PHP/RoR or it is Javascript frameworks, all make requests to a URL via the same http or https, right? Certainly, yes. Then why http has to be more secure when requests come from javascript? How does http and server know that request is coming from javascript?
When a web browser can open a URL and PHP/RoR (or any server-side language) can access that URL without any extra settings/headers, why can't AngularJS, JQuery (or in a single word javascript) access that URL unless the server has set Access-Control-Allow-Origin header for requesting root?
What's that special feature (that PHP/RoR have and) that is missing in Javascript so that it can't access the same URL in the same browsers that can open that URL without any issue from their address bars?
Just to mention that I am basically an iOS developer and recently started to learn web development, specially AngularJS. So I am curious about what's all this going on and why!
It's disabled from javascript for security reasons. Here's one scenario:
Assume Facebook has a "post message on timeline" api that requires the user to be authenticated.
You are logged into Facebook when you visit badsite.com.
badsite.com uses javascript to call the Facebook api. Since the browser is making a valid request to Facebook, your authentication cookie is sent, and Facebook accepts the message and posts badsite's ad on your timeline.
This isn't an issue from a server, because badsite.com's server doesn't have access to your Facebook authentication cookie and it can't forge a valid request on your behalf.
You remember that all javascript request is handled by browser. So browser detect cross-origin request is easy.
Request from javascript has no difference with PHP/RoR, it is only rejected by browser.
Server code can accept cross-origin javascript request by header "Access-Control-Allow-Origin" because before reject javascript request, browser will send a request "OPTIONS" to server to ask header "Access-Control-Allow-Origin" on response. If value is match with current origin, browser will accept javascript request and send to server.
All browser are implement this policy Same Origin Policy
Please read http://en.wikipedia.org/wiki/Cross-site_scripting, you will get the reason why its prohibited for JavaScript.

Restify and Angular CORS No 'Access-Control-Allow-Origin' header is present on the requested resource

I faced with that problem when implementing REST api with Restify secured with bearer token authorization type.
when I sending simple get request to API server it fails with CORS problem
405 (Method Not Allowed) angular.js:7962
OPTIONS http://api.host.com/tests No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://local.host.com' is
therefore not allowed access.
Solution described in my answer, so it's not real question for me, because I placed it when already know the answer, but hope it will save time for someone else in future.
The problem was faced because of restify has internal CORS module who manage CORS logic. in this module you could find list of allowed headers, by default it's
[
'accept',
'accept-version',
'content-type',
'request-id',
'origin',
'x-api-version',
'x-request-id'
]
As I say in the question, I use bearer token auth, so I send my request with Authorization header. It's not included in default list, and that's why my request fails.
To fix that problem we need to add this header to the list of ALLOW_HEADERS. for that in my restify configuration code I add this line:
restify.CORS.ALLOW_HEADERS.push('authorization');
Think that info could be helpfull if you faced with similar problem, because I spend a lot to find the solution.
You won't be able to access the URL http://api.host.com/tests from a file deployed at http://local.host.com due to the same-origin policy.
As the source (origin) page and the target URL are at different domains, your code is actually attempting to make a Cross-domain (CORS) request (thus the error with OPTIONS -- see the explanation below), not an ordinary GET.
In a few words, the same-origin policy enforces that browsers only allow Ajax calls to services in the same domain as the HTML page.
Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a CORS request, your browser:
Will first send an OPTION request to the target URL
And then only if the server response to that OPTIONS contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
If the expected headers don't come in the OPTIONS, the browser will give up, informing the error (that it attempted a CORS request and didn't find the necessary headers).
How to solve it?
Place the target service in the same domain of the origin page; or
Enable CORS (enable the necessary headers) on the server; or
If you don't have server-side access to the service, you could also mirror it (create a copy of it in the server you own).
JSONP is also a solution if you just want to request information (but this would require server-side access to setup as well).

Categories