Friday, 4 September 2015

Prevention Techniques: Cross-site request forgery (CSRF)

1. The best defense against CSRF attacks is unpredictable tokens, a piece of data that the server can use to validate the request, and which an attacker can’t guess. For example, an important request could contain a digest of the user’s session credential, which is different for every user. And, for a little extra security, add a timestamp to the token, to limit the window of opportunity, as shown in the POST body below:
  
POST http://fictitiousbank/transfer.cgi HTTP/1.1 
Host: fictitiousbank 
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9) Gecko/2008052906 
Firefox/3.6.2 
Cookie: PHPSESSIONID=7757ADD8766d455NFJJ23875JBJKBFR from=35367021&to48412334&amount=5000&date=05072010&token=40E03EF45T443W20K4IC567HY4334DD44&timestamp=1184001456 
   
The tokens used should also be cryptographically very strong. 
2. Challenge-Response
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.
  • CAPTCHA
  • Re-Authentication (password)
  • One-time Token
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions 
3. Limit the time for which the user’s credentials are valid. By enforcing inactivity timeouts, you reduce chances of CSRF attacks. 
4. Password re-verification should be given priority over single-sign on. In this method, the users must type in their passwords again when accessing particularly critical functions.
5. Client/User Prevention
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include:
  • Logoff immediately after using a Web application
  • Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login
  • Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing).
  • The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit. This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually.


Thursday, 3 September 2015

Cross-site request forgery (CSRF)

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF (sometimes pronounced sea-surf) or XSRF . Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. With a little help of social engineering (like sending a link via email or chat), an attacker may force the users of a web application to execute actions of the attacker's choosing. A successful CSRF exploit can compromise end user data and operation, when it targets a normal user. If the targeted end user is the administrator account, a CSRF attack can compromise the entire web application.
Example Cross-site request forgery
I just bought a new home wireless router. Like most wifi routers, it’s configured through a web interface. The router was shipped to me with an internal IP address of 192.168.1.1. I’m having trouble configuring the router though, and fortunately the folks over at somemalicioussite.com have published a guide that shows me exactly what buttons to click in the router interface to get everything set up securely. The attackers have also set up a proxy server at 123.45.67.89 that will log all traffic that goes through it and look for things like passwords and session tokens.
As I clicked through the configuration guide, I missed the 1x1 pixel image that failed to load:
<img src=”http://192.168.1.1/admin/config/outsideInterface?nexthop=123.45.67.89” alt=”pwned” height=”1” width=”1”/>
The attackers knew that when I was reading their tutorial, I would be logged into the router interface. So they had the CSRF attack set up in the tutorial. With that request, my router would be reconfigured so that my traffic will be routed to their proxy server where they can do all manner of bad things with it.
Difference between CSRF and XSS
The fundamental difference between CSRF and XSS is that cross-site scripting (XSS), is designed to exploit the trust the user has for a particular site whilst CSRF aims to exploit the trust that a website has in the visitor’s browser
Tools to test Cross-site request forgery
WebScarab Spider http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project
CSRF Tester http://www.owasp.org/index.php/Category:OWASP_CSRFTester_Project
Cross Site Requester http://yehg.net/lab/pr0js/pentest/cross_site_request_forgery.php
In the next part of this article we will discuss about the Prevention from Cross-site request forgery (CSRF)

Wednesday, 2 September 2015

Missing Function Level Access Control

When developers create web interfaces, they have to restrict which users can see various links, buttons, forms, and pages. Developers usually get this right because it is very visible. Unfortunately, making it pretty doesn’t make it secure. Developers often forget that they also have to put access controls in the business logic that actually performs business functions.
Example Missing Function Level Access Control
On my bank’s website, the clerk has a link in his navigation bar to manage the client accounts. The client can’t see that link because clients are not allowed to access this section. But the item in the menu exists in the code, it is simply hidden dynamically using a Javascript function. By analyzing the HTML code, an attacker can easily find the URL to the account management section. And as the access to this section is not controlled, thus the attacker can steal a lot of sensitive data (personal information, account data). Moreover, functions available in that account management section for clerks is not controlled either. The attacker can then transfer money to his own account. And hopefully, the attacker’s actions are not logged.
Attack Vectors Missing Function Level Access Control
Authorized user changes a URL or parameter to a privileged function.
Anonymous users could access private functions that aren’t protected.
Possible Consequences Missing Function Level Access Control
Compromised user accounts.
Compromised administrative accounts.
Unauthorized use of privileged Functionality.
Prevention Missing Function Level Access Control
Implement checks in the controller or business logic.
Don’t hard code and Audit
Deny all access by default, requiring explicit grants to specific roles for access to every function


Saturday, 22 August 2015

Top Hacking Tools as Password Cracker

Number one of the biggest security holes are passwords, as every password security study shows.
Password cracking is the process of recovering passwords from data that have been stored in or transmitted by a computer system. Password cracking isn't done by trying to log in to, say, a bank's website millions of times; websites generally don't allow many wrong guesses, and the process would be unbearably slow even if it were possible. The cracks always take place offline after people obtain long lists of "hashed" passwords, often through hacking.

Below are the top Hacking Tools used as a Password cracker
Cain & Abel is a password recovery tool for Microsoft Operating Systems. It allows easy recovery of various kinds of passwords by sniffing the network, cracking encrypted passwords using Dictionary, Brute-Force and Cryptanalysis attacks, recording VoIP conversations, decoding scrambled passwords, recovering wireless network keys, revealing password boxes, uncovering cached passwords and analyzing routing protocols. The program does not exploit any software vulnerabilities or bugs that could not be fixed with little effort. It covers some security aspects/weakness present in protocol's standards, authentication methods and caching mechanisms; its main purpose is the simplified recovery of passwords and credentials from various sources, however it also ships some "non standard" utilities for Microsoft Windows users.
THC Hydra is a fast and flexible Network Login Hacking Tool. It uses a dictionary attack to try various password/login combinations against an Internet service to determine a valid set of login credentials. It supports a wide set of protocols including Mail (POP3, IMAP, etc.), Databases, LDAP, SMB, VNC, and SSH.
Ophcrack is a free open source (GPL licensed) program that cracks Windows passwords by using LM hashes through rainbow tables. The program includes the ability to import the hashes from a variety of formats, including dumping directly from the SAM files of Windows. On most computers, ophcrack can crack most passwords within a few minutes.
John the Ripper is a free password cracking software tool. Initially developed for the Unix operating system, it now runs on fifteen different platforms (eleven of which are architecture-specific versions of Unix, DOS, Win32, BeOS, and OpenVMS). It is one of the most popular password testing and breaking programs as it combines a number of password crackers into one package, autodetects password hash types, and includes a customizable cracker. It can be run against various encrypted password formats including several crypt password hash types most commonly found on various Unix versions (based on DES, MD5, or Blowfish), Kerberos AFS, and Windows NT/2000/XP/2003 LM hash. Additional modules have extended its ability to include MD4-based password hashes and passwords stored in LDAP, MySQL, and others.
Medusa is intended to be a speedy, massively parallel, modular, login brute-forcer. The goal is to support as many services which allow remote authentication as possible. The author considers following items as some of the key features of this application:
  • Thread-based parallel testing. Brute-force testing can be performed against multiple hosts, users or passwords concurrently.
  • Flexible user input. Target information (host/user/password) can be specified in a variety of ways. For example, each item can be either a single entry or a file containing multiple entries. Additionally, a combination file format allows the user to refine their target listing.
  • Modular design. Each service module exists as an independent .mod file. This means that no modifications are necessary to the core application in order to extend the supported list of services for brute-forcing.

Wednesday, 19 August 2015

Top Hacking Tools for Exploitation

A good Exploitation tool is a framework of several services and tools not only limited to identify a vulnerable remote host and all the attacks we can perform on that particular remote host but actually exploit the host, offering a shell or various other functions on the remote host.  Below are the Top Hacking Tools for Vulnerability Exploitation.
Metasploit Framework, a tool for developing and executing exploit code against a remote target machine. It is an advanced open-source platform for developing, testing, and using exploit code. The extensible model through which payloads, encoders, no-op generators, and exploits can be integrated has made it possible to use the Metasploit Framework as an outlet for cutting-edge exploitation research. It ships with hundreds of exploits, as you can see in their list of modules.
Core Impact Pro is widely considered to be the most powerful exploitation tool available. Core Impact Pro is the most comprehensive software solution for assessing and testing security vulnerabilities throughout your organization.
•Endpoint systems
•Passwords and identities
•Mobile devices
•Wireless networks
•Web applications and services
•Network systems and devices
Immunity's CANVAS makes available hundreds of exploits, an automated exploitation system, and a comprehensive, reliable exploit development framework to penetration testers and security professionals worldwide. The strength of Canvas is that it provides one of the most flexible and powerful frameworks for exploitation, intrusion detection device testing, and exploit crafting. However, that very flexibility combined with its GUI makes.
 A web application security testing framework built on top of a browser. Supports Windows, Linux and Macintosh.  Mantra has many built in tools to modify headers, manipulate input strings, replay GET/POST requests, edit cookies, quickly switch between multiple proxies, control forced redirects etc. This makes it good software for performing basic security checks and sometimes, exploitation.
Amid growing concerns about web-borne attacks against clients, including mobile clients, BeEF allows the professional penetration tester to assess the actual security posture of a target environment by using client-side attack vectors. Unlike other security frameworks, BeEF looks past the hardened network perimeter and client system, and examines exploitability within the context of the one open door: the web browser.

Wednesday, 12 August 2015

Tutorials, Cheat Sheet and Tools for Hacking

In the following tutorial we will learn how to hack anyone's computer and android mobile phone
Hacking Android phone using Metasploit
http://infosecaffairs.blogspot.in/2014/11/hacking-android-phone-using-metasploit.html
Hack anyone’s computer by using malicious PDF
http://infosecaffairs.blogspot.in/2014/11/hack-anyones-computer-by-using-malicious-PDF.html

Cheat sheets aren't only meant for programmers. Rather, with the number of things that they have to know, hackers often require cheat sheets too. When it comes to hacking, it's always good to have a few sheets. Below are the sheets you can use while hacking.
Google Dorks List for SQL injection
http://infosecaffairs.blogspot.in/2014/10/google-dorks-list-for-sql-injection_16.html
Remote file inclusion (RFI) dork list
http://infosecaffairs.blogspot.in/2014/11/remote-file-inclusion-rfi-dork-list.html
Sqlmap cheat sheet
http://infosecaffairs.blogspot.in/2014/10/sqlmap-cheat-sheet.html
Password Cracking: Dictionary Attack Password List
http://infosecaffairs.blogspot.in/2014/10/password-cracking-dictionary-attack-Password-List.html

As an information security professional, your toolkit is the most critical item you can possess. Following are the tools and applications you can use while hacking
Penetration Testing Apps for Android Devices
http://infosecaffairs.blogspot.in/2014/09/penetration-testing-apps-for-android.html
Tools to hack WiFi
http://infosecaffairs.blogspot.in/2014/11/tools-to-hack-wifi.html
DDOS Attack and Free Tools for DDOS
http://infosecaffairs.blogspot.in/2014/10/ddos-attack-and-tools-for-ddos.html 
Top Hacking Tools as Password Cracker
http://infosecaffairs.blogspot.in/2015/08/top-hacking-tools-as-password-cracker.html
Top Hacking Tools for Exploitation
http://infosecaffairs.blogspot.in/2015/08/top-hacking-tools-for-exploitation.html

Sunday, 26 July 2015

Sensitive Data Exposure Vulnerabilities

Sensitive data exposure vulnerabilities can occur when an application does not adequately protect sensitive information from being disclosed to attackers. For many applications this may be limited to information such as passwords, but it can also include information such as credit card data, session tokens, or other authentication credentials.
Example
Scenario #1: An application encrypts credit card numbers in a database using automatic database encryption. However, this means it also decrypts this data automatically when retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text. The system should have encrypted the credit card numbers using a public key, and only allowed back-end applications to decrypt them with the private key.
Scenario #2: A site simply doesn’t use SSL for all authenticated pages. Attacker simply monitors network traffic (like an open wireless network), and steals the user’s session cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s private data.
Testing of Sensitive data exposure vulnerabilities
The first thing you have to determine is which data is sensitive enough to require extra protection. For example, passwords, credit card numbers, health records, and personal information should be protected. For all such data:
*Is any of this data stored in clear text long term, including backups of this data?
*Is any of this data transmitted in clear text, internally or externally? Internet traffic is especially dangerous.
*Are any old / weak cryptographic algorithms used?
*Are weak crypto keys generated, or is proper key management or rotation missing?
*Are any browser security directives or headers missing when sensitive data is provided by / sent to the browser?
Prevention of Sensitive data exposure vulnerabilities
· Encrypt all sensitive data at rest and in transit in a manner that defends against these threats.
· Don’t store sensitive data unnecessarily. Discard it as soon as possible. Data you don’t have can’t be stolen.
· Disable auto complete on forms collecting sensitive data and disable caching for pages that contain sensitive data.

Saturday, 25 July 2015

Directory Listing/Indexing

Directory listing is a web server function that displays a list of all the files when there is not an index file, such as index.php and default.asp in a specific website directory.
For example, when a user requests www.infosecaffairs.com without specifying a file, the web server will process this request and will return the index file for that directory and the actual website will show up. However, if the index file does not exist, the web server will return a list of the contents of that directory. This functionality can be parallelized with the directory listing command in operating systems’ command line, such as ‘ls’ on Unix and Linux systems and ‘dir’ on Windows. Furthermore, it should be noted that the Directory Listing might be caused as well by exploiting any software vulnerabilities using special requests
Background of Directory Listing/Indexing
When a web server reveals a directory's contents, the listing could contain information not intended for public viewing. Often web administrators rely on "Security Through Obscurity" assuming that if there are no hyperlinks to these documents, they will not be found, or no one will look for them. The assumption is incorrect. Today's vulnerability scanners, such as Wikto, can dynamically add additional directories/files to include in their scan based upon data obtained in initial probes. By reviewing the /robots.txt file and/or viewing directory indexing contents, the vulnerability scanner can now interrogate the web server further with these new data. Although potentially harmless, Directory Indexing could allow an information leak that supplies an attacker with the information necessary to launch further attacks against the system
Example
A user makes a website request to www.example.com/images/. The response from the server includes the directory listing content of the directory images, as seen in the below screenshot. 

Impact/ Information Disclosed
The following information could be obtained based on directory indexing data:
*Backup files - with extensions such as .bak, .old or .orig
*Temporary files - these are files that are normally purged from the server but for some reason are still available
*Hidden files - with filenames that start with a "." period.
*Naming conventions - an attacker may be able to identify the composition scheme used by the web site to name directories or files. Example: Admin vs. admin, backup vs. back-up, etc...
*Enumerate User Accounts - personal user accounts on a web server often have home directories named after their user account.
*Configuration file contents - these files may contain access control data and have extentions such as .conf, .cfg or .config
*Script Contents - Most web servers allow for executing scripts by either specifying a script location (e.g. /cgi-bin) or by configuring the server to try and execute files based on file permissions (e.g. the execute bit on *nix systems and the use of the Apache XBitHack directive). Due to these options, if directory indexing of cgi-bin contents are allowed, it is possible to download/review the script code if the permissions are incorrect.
Prevention of Directory Listing/Indexing
Disable directory listings in the web- or application-server configuration by default.
Restrict access to unnecessary directories and files.
Create an index (default) file for each directory.

Friday, 24 July 2015

Security Misconfiguration Vulnerability

Incorrect or Ineffective implementation of security at any layer of a system causes Security Misconfiguration Vulnerability. Security Misconfiguration, or poorly configured security controls, could allow malicious users to change your website, obtain unauthorized access, compromise files, or perform other unintended actions.
Security Misconfiguration can happen at any level of an application stack, including the platform, web server, application server, database, framework, and custom code. Developers and system administrators need to work together to ensure that the entire stack is configured properly.
Example Attack Scenarios
Scenario #1: The app server admin console is automatically installed and not removed. Default accounts aren’t changed. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over.
Scenario #2: Directory listing is not disabled on your server. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which she decompiles and reverse engineers to get all your custom code. She then fined a serious access control flaw in your application.
Scenario #3: App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide.
Scenario #4: App server comes with sample applications that are not removed from your production server. Said sample applications have well known security flaws attackers can use to compromise your server.

Prevention from Security Misconfiguration
*Regularly evaluate your Website and its environment, including the Web server, operating system, applications, and other resources your Website uses. While there is no one-size-fits-all security configuration, you can use these points to develop a plan that works for your situation:
*Keep third-party applications up to date. Check vendor's websites for updates, and install the most recent release.
*Change default user names and passwords. Use strong, unique passwords for every account.
*Disable directory listings if they are not necessary, or set access controls to deny all requests.
*Delete unnecessary files, such as configuration or install files.
*Keep private or internal data separate from public data. Use strong encryption for anything sensitive.
*Back up data regularly, and store backups appropriately.
*Set and review access controls, and update them as necessary.
*Consider running scans and doing audits periodically to help detect future misconfiguration or missing patches.

Thursday, 23 July 2015

Insecure Direct Object References Series: Prevention of Insecure Direct Object Reference

1. Access Control Check:
One essential defense is to check access control. On each use of a direct object reference from an untrusted source, the application should perform an access control check to ensure the user is authorized for the requested object or service. One way to implement this is to use role-based authorization. The idea behind is associating a list of roles with a user, and the service code queries the list to make decisions about whether the user has privilege to access the requested object or service at run time.
2. Indirect Reference Map:
An indirect reference map is a substitution of the internal reference with an alternate ID. It is used for mapping from a set of internal direct object references (i.e. database keys, filenames, etc. ) to a set of indirect reference that can be safely exposed externally
The direct references are user IDs that are integer and auto-incrementing. Take this as an example; an indirect reference map can be implemented as follows:
  • a) Create a map on the server between that actual key, user ID in the database (i.e. 1011, 1012, ...), and the substitution, which can be a long hash value or a GUID that is easily generated but difficult to predicted by users
  • b) The user ID is translated to its substitution key before being exposed to the UI.
  • c) After the substitution key is returned to the server, it is translated back to the original user ID before the record is retrieved.
3. Use per user or session indirect object references.
This prevents attackers from directly targeting unauthorized resources. For example, instead of using the resource’s database key, a drop down list of six resources authorized for the current user could use the numbers 1 to 6 to indicate which value the user selected. The application has to map the per-user indirect reference back to the actual database key on the server.
4. Don’t expose the actual ID/name of objects
5. Minimize user ability to predict object IDs/Names
6. Use of ESAPI

Wednesday, 22 July 2015

Insecure Direct Object References Series : Test/Detect Insecure Direct Object References Vulnerability

Generally, the first step of testing this vulnerability is to “map out all locations in the application where user input is used to reference objects directly” .These locations include where user input is used to access a database row, a file, application pages, etc. Secondly, modify the value of the parameter used to reference objects and assess whether it is possible to retrieve objects belonging to other users and whether authorization can be bypassed.

Static Analysis
One important approach is code review of the application and verifies whether the following mechanisms are implemented safely:
(1) For direct references to restricted resources, the application needs to verify the user is authorized to access the exact resource they have requested.
(2) If the reference is an indirect reference, the mapping to the direct reference must be limited to values authorized for the current user.
Dynamic Analysis
One way to test would be by having multiple users to cover different owned objects and functions. For example, assume two users each having access to different objects and with different privileges (i.e. administrator users or normal users). Logon as one user to see whether there are direct references to objects or functionality that belong to other users. Another advantage of having multiple users is to save testing time in guessing different object names that belong to other users.
Typical scenarios for this vulnerability and the methods to test for each include:
The value of a parameter is used directly to retrieve a database record
Sample request:
                         http://foo.bar/somepage?invoice=12345
In this case, the value of the invoice parameter is used as an index in an invoices table in the database. The application takes the value of this parameter and uses it in a query to the database. The application then returns the invoice information to the user.
Since the value of invoice goes directly into the query, by modifying the value of the parameter it is possible to retrieve any invoice object, regardless of the user to whom the invoice belongs. To test for this case the tester should obtain the identifier of an invoice belonging to a different test user (ensuring he is not supposed to view this information per application business logic), and then check whether it is possible to access objects without authorization.
The value of a parameter is used directly to perform an operation in the system
Sample request:
                         http://foo.bar/changepassword?user=someuser
In this case, the value of the user parameter is used to tell the application for which user it should change the password. In many cases this step will be a part of a wizard, or a multi-step operation. In the first step the application will get a request stating for which user's password is to be changed, and in the next step the user will provide a new password (without asking for the current one).
The user parameter is used to directly reference the object of the user for whom the password change operation will be performed. To test for this case the tester should attempt to provide a different test username than the one currently logged in, and check whether it is possible to modify the password of another user.
The value of a parameter is used directly to retrieve a file system resource
Sample request:
                         http://foo.bar/showImage?img=img00011

In this case, the value of the file parameter is used to tell the application what file the user intends to retrieve. By providing the name or identifier of a different file (for example file=image00012.jpg) the attacker will be able to retrieve objects belonging to other users.
To test for this case, the tester should obtain a reference the user is not supposed to be able to access and attempt to access it by using it as the value of file parameter.
The value of a parameter is used directly to access application functionality
Sample request:
                         http://foo.bar/accessPage?menuitem=12
In this case, the value of the menu item parameter is used to tell the application which menu item (and therefore which application functionality) the user is attempting to access. Assume the user is supposed to be restricted and therefore has links available only to access to menu items 1, 2 and 3. By modifying the value of menu item parameter it is possible to bypass authorization and access additional application functionality. To test for this case the tester identifies a location where application functionality is determined by reference to a menu item, maps the values of menu items the given test user can access, and then attempts other menu items.
In the next part of the Insecure Direct Object References Series we will talk about some Insecure Direct Object Reference Prevention techniques

Tuesday, 21 July 2015

Insecure Direct Object References Series: Introduction and Why Vulnerability Occur

Introduction
Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for example database records or files.
Insecure Direct Object Reference is an attack where attacker who is an authenticated system user, simply changes a parameter value that directly refers to a system object or another object the user isn’t authorized for. An attacker can manipulate direct object references to access other objects without authorization, unless an access control check is in place.
By exploiting Insecure Direct Object References, attackers can bypass authorization and access resources directly by modifying the value of a parameter used to directly point to an object ( i.e. by modifying the user account ID in a URL string to access the information of other users) . The potentially accessed resources can be database entries belong to other users, files in the system, and more
Why Insecure Direct Object References Vulnerability occurs
From the cases and examples presented above, we can see that insecure direct object typically caused by several design flaws, such as lack of access control, using direct reference to internal object that is exposed and predictable ( i.e. customer ID are easily guessed because it is integer and auto incrementing ).
In the next part of the Insecure Direct Object References Series we will talk about how to Test/Detect Insecure Direct Object References Vulnerability in the web application

Monday, 20 July 2015

Site Scripting Series: Cross Site Scripting Prevention techniques

1. Data Validation
Data validation is the process of ensuring that your application is running with correct data. If your PHP script expects an integer for user input, then any other type of data would be discarded. Every piece of user data must be validated when it is received to ensure it is of the corrected type, and discarded if it doesn’t pass the validation process.
2. Data Sanitization
Data sanitization focuses on manipulating the data to make sure it is safe by removing any unwanted bits from the data and normalizing it to the correct form
3. Encoding
Encoding is the act of escaping user input so that the browser interprets it only as data, not as code. The most recognizable type of encoding in web development is HTML escaping, which converts characters like < and > into &lt; and &gt;, respectively.
The following pseudocode is an example of how user input could be encoded using HTML escaping and then inserted into a page by a server-side script:
     print "<html>"
     print "Latest comment: "
     print encodeHtml(userInput)
     print "</html>"
If the user input were the string <script>...</script>, the resulting HTML would be as follows:
    <html>
    Latest comment:
    &lt;script&gt;...&lt;/script&gt;
    </html>
Because all characters with special meaning have been escaped, the browser will not parse any part of the user input as HTML.
4. Auto-Escaping and Context-Aware Escaping templates
Sometimes it is advantageous to have everything assigned to Smarty automatically HTML-escaped to reduce the risks of XSS (cross-site scripting) vulnerabilities.
5. Content-security policy
Content-security policy is as a source whitelist. Typically when we make a request for a web page, our browsers trusts output that the server is delivering. CSP limits this trust model by sending Content-Security-Policy header that allows the application to specify a whitelist of trusted (expected) sources. When the browser receives this header, it will only render or execute resources from those sources.
In the event that an attacker does have the ability to inject malicious content that is reflected back against the user, the script will not match the whitelist, and will not be executed.
Example 1: A server wishes to load resources only from its own origin:
                  Content-Security-Policy: default-src 'self'
Example 2: An auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
         Content-Security-Policy: default-src 'self'; img-src *; object-src media1.example.com                  media2.example.com *.cdn.example.com; script-src trustedscripts.example.com
Example 3: Online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
          Content-Security-Policy: default-src https: 'unsafe-inline' 'unsafe-eval'
Example 4: A website that relies on inline script elements wishes to ensure that script is only executed from its own origin, and those elements it intentionally inserted inline:
          Content-Security-Policy: script-src 'self' 'nonce-$RANDOM';
The inline script elements would then only execute if they contained a matching nonce attribute:             <script nonce="$RANDOM">...</script>
6. Javascript sandbox tools
7. Cookie security
Many web applications tie session cookies to the IP address of the user who originally logged in, and only permit that IP to use that cookie. This is effective in situations like if an attacker is only after the cookie
HTTP-only cookies: Http-Only flag allows a web server to set a cookie that is unavailable to client-side scripts. It disables client access via document.cookie and mitigates cookie theft via XSS
8. Application Firewall
By installing a third party application firewall, which intercepts XSS attacks before they reach the web server and the vulnerable scripts, and blocks them. For each input source, the application firewall inspects the data against various HTML tag patterns and Javascript patterns, and if any match, the request is rejected and the malicious input does not arrive to the server.
A full detailed guide to prevent XSS is also available on OWASP. You can read it here.

Sunday, 19 July 2015

Cross Site Scripting Series: Impact and Test Cross Site Scripting

Impact of Cross-Site Scripting
When attackers succeed in exploiting XSS vulnerabilities, they can gain access to account credentials. They can also spread web worms or access the user’s computer and view the user’s browser history or control the browser remotely. After gaining control to the victim’s system, attackers can also analyze and use other intranet applications.
By exploiting XSS vulnerabilities, an attacker can perform malicious actions, such as:
  • Hijack an account.
  • Spread web worms.
  • Access browser history and clipboard contents.
  • Control the browser remotely.
  • Scan and exploit intranet appliances and applications.
Test Cross-Site Scripting
A sample test is shown here against the most common parameter: the GET request. When the URL includes some parameter like title, it can be attempted to exploit directly in the browser:
           Page.php?title=<SCRIPT>alert("attack")</SCRIPT>
For each of the attack vectors described, you can test them in the following ways:
· GET - modify the parameter to an XSS string
· POST - insert the XSS string into a form field, or using an attack proxy
· Headers - modify a header to an XSS string
· Window.location - if using input in the new URL, try appending javascript
· document.referrer - Modify the referrer (header) to an XSS string
· document.URLUnencoded- The function returns the unencoded URL, so include a URL encoded XSS string in the URL to test this.
· Cookies - Inspect and modify the cookie values on your PC for testing. Insert XSS attacks in the cookie
Alternate Cross-Site Scripting Syntax
XSS using Script in Attributes

XSS attacks may be conducted without using <script></script> tags. Other tags will do exactly the same thing, for example:
             <body onload=alert('test1')>
             or other attributes like: onmouseover, onerror.
            onmouseover <b onmouseover=alert('Wufff!')>click me!</b>
            onerror <img src="http://url.to.file.which/not.exist" onerror=alert(document.cookie);>
XSS using Script Via Encoded URI Schemes
If we need to hide against web application filters we may try to encode string characters, e.g.: a=&#X41 (UTF-8) and use it in IMG tag: <IMG SRC=j&#X41vascript:alert('test2')>
There are many different UTF-8 encoding notations what give us even more possibilities.
XSS using code encoding
We may encode our script in base64 and place it in META tag. This way we get rid of alert() totally.      
          <META HTTP-EQUIV="refresh"
           CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg">
These and others examples can be found at the OWASP XSS Filter Evasion Cheat Sheet which is a true encyclopaedia of the alternate XSS syntax attack.In the next part of the Cross Site Scripting Series we will talk about the CrossSite Scripting Prevention techniques.

Saturday, 18 July 2015

Cross-Site Scripting Series :Types of Cross-Site Scripting

Stored Cross-Site Scripting
Stored attacks are those where the injected script is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information. Stored XSS is also sometimes referred to as Persistent or Type-I XSS.
1. The attacker uses one of the website's forms to insert a malicious string into the website's database.
2. The victim requests a page from the website.
3. The website includes the malicious string from the database in the response and sends it to the victim.
4. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server.
Reflected Cross-Site Scripting
Reflected attacks are those where the injected script is reflected off the web server, such as in an error message, search result, or any other response. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web site. When a user is tricked into clicking on a malicious link, submitting a specially crafted form, or even just browsing to a malicious site, the injected code travels to the vulnerable web site, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a "trusted" server. Reflected XSS is also sometimes referred to as Non-Persistent or Type-II XSS.
1. The attacker crafts a URL containing a malicious string and sends it to the victim.
2. The victim is tricked by the attacker into requesting the URL from the website.
3. The website includes the malicious string from the URL in the response.
4. The victim's browser executes the malicious script inside the response, sending the victim's cookies to the attacker's server.
DOM-based Cross-Site Scripting
The DOM, or Document Object Model, is the structural format used to represent documents in a browser. The DOM enables dynamic scripts such as JavaScript to reference components of the document such as a form field or a session cookie.
In a DOM-based XSS attack, the malicious string is not actually parsed by the victim's browser until the website's legitimate JavaScript is executed. DOM based XSS does not require the web server to receive the malicious XSS payload. Instead, in a DOM-based XSS, the attacker abuses runtime embedding of attacker data in the client side, from within a page served from the web server.
DOM-based Cross-Site Scripting occurs when script manipulates the pages DOM allowing an attacker to run script on victim browser. DOM-based Cross-Site Scripting will observed in run time only not in source code or not in response
1. The attacker crafts a URL containing a malicious string and sends it to the victim.
2. The victim is tricked by the attacker into requesting the URL from the website.
3. The website receives the request, but does not include the malicious string in the response.
4. The victim's browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page.
5. The victim's browser executes the malicious script inserted into the page, sending the victim's cookies to the attacker's server.

In the next part of the Cross-Site Scripting Series we will talk about the impact of Cross-Site Scripting and how to test Cross-SiteScripting
References
http://excess-xss.com/

Friday, 17 July 2015

Cross-Site Scripting Series: Inroduction

Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user's browser, often causing side effects such as data compromise, or the stealing of a user session. This can allow an attacker to impersonate a user to steal their details, or act in their place without consent.XSS Flaws occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. 
Description of Cross-Site Scripting
Cross-Site Scripting (XSS) attacks occur when:
· Data enters a Web application through an untrusted source, most frequently a web request.
· The data is included in dynamic content that is sent to a web user without being validated for malicious content.
The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash, or any other type of code that the browser may execute. A successful XSS attack compromises the security of both the website and its users.
XSS vulnerability arises when web applications take data from users and dynamically include it in web pages without first properly validating the data. XSS vulnerabilities allow an attacker to execute arbitrary commands and display arbitrary content in a victim user's browser. A successful XSS attack leads to an attacker controlling the victim’s browser or account on the vulnerable web application.
Example
     
index.php: <?php
$name = $_GET['name'];
echo "Welcome $name<br>";
echo "<a href="http://infosecaffairs.blogspot.com/">Click to Download</a>";
?>
Now the attacker will craft an URL as follows and send it to the victim:
   
index.php?name=guest<script>alert('XSS')</script>
    
When the victim loads the above URL into the browser, he will see an alert box which says ‘attacked’. Even though this example doesn’t do any damage, other than the annoying ‘attacked’ pop-up, you can see how an attacker can use this method to do several damaging things.
In the next part of the series we will discuss about the Types of XSS vulnerabilities

Prevention Techniques: Cross-site request forgery (CSRF)

1. The best defense against CSRF attacks is unpredictable tokens, a piece of data that the server can use to validate the request, and wh...