Above code will not work. In order to make it work the very first
element passed to the callback must be an event object. Here is the code
that will work.
The thing about trigger method is that the event object is always passed as the first parameter to the event handler. This is why when you are using jquery-ujs you have to have the first parameter in the callback function an event object.
XSS vulnerability allows hacker to execute JavaScript code.
Your site has a form. I enter <script>alert(document.cookie)</script> and I hit submit. If I see an alert then it means I can execute JavaScript code on your site and your site has XSS vulnerability.
If a hacker can execute JavaScript code then the hacker can see your cookie.
If you are logged into your application then your application sets a
cookie. That is how your application knows that you are logged in.
If a hacker can see your cookie then the hacker can log in.
By the way having SSL does not protect the site from XSS vulnerability.
Prevention
An easy way to prevent XSS is to not to allow users to execute JavaScript
code. This is the reason why when you go to post comment many sites have
messages similar to this one.
Some sites allow some html code and other do not allow any html code at
all.
It is possible for the hacker to insert JavaScript code in your system.
For example if database stores <script>alert(document.cookie)</script>
then JavaScript code has come inside the application. However
as long as you deny the opportunity for that code to be executed in
browser you are safe.
You can also take precaution and sanitize all user input so that
JavaScript code does not comes into the system at all.
The right approach depends on your need and the application framework
you are working with.
A practical example
It is very commont to display address in a formatted way. Usually the
code is something like this
Since here the address is being separated by an html tag <br />. When
developer looks at the html page he/she sees the <br /> tag literally
on the screen so the developer comes back to code and marks the string
as html_safe.
Now the browser renders the address with proper <br /> tag and the
address looks nicely formatted. The developer moves on.
However notice that developer has marked user input data like address1
as html_safe and as I discussed earlier this is exposing your site to
XSS attack.
Here is how it should be fixed without exposing any security issue.
Notice that user input elements are being subjected to html_escape
before they are marked as html_safe.
What tools Rails provides
In the earlier version of Rails we were encouraged to use <%= h post.comment %> in views. Here h is a short name for html_escape. In Rails 3.x the content is automatically escaped. It means if the hacker enters <script>alert(document.cookie)</script> then after html_escape has performed its operation the browser sees "<script>alert(document.cookie)</script>". In this way the user does not get to see the alert message which is a good thing. It means users cannot execute JavaScript code on your site and your site is XSS safe.
If you do want to format the text a little bit then you can use
simple_format . If user enters a bunch of text in text area then simple_format can help make the text look pretty without compromising security. It will strip away <script> and security sensitive tags. html_escape internally uses sanitize method. Checkout that method to see what options you can pass. Think before you act because you might be opening a security vulnerability.
Also be careful with raw method. It will output without escaping the string.
In case of Json you need to handle escaping yourself
Note that when user entered <script>alert(document.cookie)</script> in
the textarea then database stored the value as <script>alert(document.cookie)</script> . No escaping is done before storing the value in the database. It is the ERB that does the escaping and ensures that site is protected.
All is well and after a few months boss comes and asks to make that page ajaxy. Now data is sent to browser in JSON format.
Now Controller looks like format.json { render json: @user }.
This will produce JSON structure
like this "{\"about\":\"<script>alert(document.cookie)</script>\"}".
On the client side you have code to display the content.
$('body').append(data.about). Well when the about content is added to
dom the script will be executed and now your site is vulnerable to XSS.
You would think that using json_escape should solve the problem. However json_escape produces invalid JSON. Yes that is right. The output of json_escape is invalid JSON. There is an open pull request to take care of that issue.
The point is that if you are passing JSON data to be displayed on the
browser then , by default, you do not have the escape protection that
ERB provides.
Unlike XSS CSRF does not try to steal your informationt to log into the system. CSRF assumes that you are aleady logged in at your site and when you visit comments section of some other site then an attack is done on your site without you knowing it.
Here is how it might work
User logs in at www.mysite.com .
User visits www.gardening.com site since he is interested in gardeing
.
He is browsing the comments posted on the gardening.com forum and one of the comments posted is <img src="http://www.mysite.com/grant_access?user_id=1&project_id=123" />
If the user is admin of the project “123” then unknowingly he might
grant access to user_id 1 .
I know. You are thiniking that loading an image will make a GET
request and granting access is hidden behind POST request. So you are
safe. Well the hacker can easily change code to make a POST request.
The code might look like this
The exact value of the authenticity_token will be different. When form
is submitted then Rails checks the authenticity_token and only when it is verified the request is sent for further processing.
In a brand new rails application the application_controller.rb has
only one line.
That line protect_from_forgery checks for the authentication of the
incoming request.
Here is code that is responsible for generating csrf_token.
1234
# Sets the token value for the current session.defform_authenticity_tokensession[:_csrf_token]||=SecureRandom.base64(32)end
Since this “csrf_token” is a random value there is no way for hacker to
know what the “csrf_token” is for my session. And he will not be able to
pass the correct “authenticity_token”.
Note that if the site is vulnerable to XSS then the hacker submits
request as if he is logged in and in that case the CSRF attack will go
through.
You have been assigned the task of figuring out in what order following tasks should be executed given their dependencies on other tasks.
12345
Task11 takes input from task5 and task7.
Task10 takes input from task11 and task3.
Task9 takes input from task8 and task11.
Task8 takes input from task3 and task7.
Task2 takes input from task11.
If you look at these tasks and draw a graph then it might look like this.
Directed acyclic graph
The graph shown above is a “Directed acyclic graph” . In Directed acyclic graphs if you start following the arrow then you should never be able to get to the node from where you started.
Directed acyclic graphs are great at describing problems where a task is dependent on another set of tasks.
We started off with a set of tasks that are dependent on another set of tasks. To get the solution we need to sort the tasks in such a way that first task is not dependent on any task and the next task is only dependent on task previously done. So basically we need to sort the directed acyclic graph such that the prerequisites are done before getting to the next task.
Sorting of directed acyclic graph in the manner described above is called topological sorting .
If I execute above code in ruby 1.9.2 I get following result.
12345678
r5r2r11r3r10r7r8r9
So that is the order in which tasks should be executed .
How Tsort works
tsort requires that following two methods must be implemented.
#tsort_each_node - as the name suggests it is used to iterate over all
the nodes in the graph. In the above example all the requrirements are
stored as a hash key . So to iterate over all the nodes we need to go
through all the hash keys. And that can be done using #each_key method
of hash.
#tsort_each_child - this method is used to iterate over all the child
nodes for the given node. Since this is directed acyclic graph all the child
nodes are the dependencies. We stored all the dependencies of a project
as an array. So to get the list of all the dependencies for a node all
we need to do is @requirements[name].each.
Another example
To make things clearer lets try to solve the same problem in a different
way.
When Rails boots it invokes a lot of initializers. Rails uses tsort to get the order in which initializers should be invoked. Here is the list of unsorted initializers. After sorting the initializers list is this .
Where else it is used
Bundler uses tsort to find the order in which gems should be installed.
Tsort can also be used to statically analyze programming code by looking at method dependency graph.
With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.
This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.
Overall my recommendation would be to use alias_method. Since alias_method is a method defined in class Module it can be overridden later and it offers more flexibility.
Backbone.js users use bind and bindAll methods provide by underscore.js a lot. In this blog I am going to discuss why these methods are needed and how it all works.
It all starts with apply
Function bindAll internally uses bind . And bind internally uses apply. So it is important to understand what apply does.
1234
varfunc=functionbeautiful(){alert(this+' is beautiful');};func();
If I execute above code then I get [object window] is beautiful. I am getting that message because when function is invoked then this is window, the default global object.
In order to change the value of this we can make use of method apply as given below.
1234
varfunc=functionbeautiful(){alert(this+' is beautiful');};func.apply('Internet');
In the above case the alert message will be Internet is beautiful . Similarly following code will produce Beach is beautiful .
1234
varfunc=functionbeautiful(){alert(this+' is beautiful');};func.apply('Beach');//Beach is beautiful
In short, apply lets us control the value of this when the function is invoked.
Why bind is needed
In order to understand why bind method is needed first let’s look at following example.
Above example is pretty straight forward. john is an instance of Developer and when says function is invoked then we get the right alert message.
Notice that when we invoked says we invoked like this john.says(). If we just want to get hold of the function that is returned by says then we need to do john.says. So the above code could be broken down to following code.
Above code is similar to the code above it. All we have done is to store the function in a variable called func. If we invoke this function then we should get the alert message we expected. However if we run this code then the alert message will be undefined rocks!.
We are getting undefined rocks! because in this case func is being invoked in the global context. this is pointing to global object called window when the function is executed. And window does not have any attribute called skill . Hence the output of this.skill is undefined.
Earlier we saw that using apply we can fix the problem arising out of this. So lets try to use apply to fix it.
Above code fixes our problem. This time the alert message we got was Ruby rocks!. However there is an issue and it is a big one.
In JavaScript world functions are first class citizens. The reason why we create function is so that we can easily pass it around. In the above case we created a function called func. However along with the function func now we need to keep passing john around. That is not a good thing. Secondly the responsibility of rightly invoking this function has been shifted from the function creator to the function consumer. That’s not a good API.
We should try to create functions which can easily be called by the consumers of the function. This is where bind comes in
To solve the problem regarding this issue we need a function that is already mapped to john so that we do not need to keep carrying john around. That’s precisly what bind does. It returns a new function and this new function has this bound to the value that we provide.
Above code is similar to bind solution but there are some big differences.
The first big difference is that we do not have to worry about the returned value of bindAll . In case of bind we must use the returned function. In bindAll we do not have to worry about the returned value but it comes with a price. bindAll actually mutates the function. What does that mean.
See john object has an attribute called says which returns a function . bindAll goes and changes the attribute says so that when it returns a function, that function is already bound to john.
Herer is a snippet of code from bindAll method.
1
function(f){obj[f]=_.bind(obj[f],obj);}
Notice that bindAll internally calls bind and it overrides the existing attribute with the function returned by bind.
The other difference between bind and bindAll is that in bind first paramter is a function john.says and the second parameter is the value of this john. In bindAll first paramter is value of this john and the second parameter is not a function but the attribute name.
Things to watch out for
While developing a Backbone.js application someone had code like this