Showing posts with label Cross Site Scripting (XSS). Show all posts
Showing posts with label Cross Site Scripting (XSS). Show all posts

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

Thursday, 7 May 2015

Million WordPress user vulnerable to DOM-based XSS



Million WordPress user vulnerable to DOM-based XSS

Any WordPress Plugin or theme that leverages the genericons package is vulnerable to a DOM-based Cross-Site Scripting (XSS) vulnerability due to an insecure file included with genericons. JetPack and TwentyFifteen Vulnerable to DOM-based XSS. 

DOM XSS
DOM Based XSS simply means a Cross-site scripting vulnerability that appears in the DOM (Document Object Model) instead of part of the HTML. DOM XSS is a type of cross site scripting attack which relies on inappropriate handling, in the HTML page, of the data from its associated DOM. Among the objects in the DOM, there are several which the attacker can manipulate in order to generate the XSS condition, and the most popular, from this perspective, are the document.url, document.location and document.referrer objects.
Any plugin that makes use of this package is potentially vulnerable if it includes the example.html file that comes with the package.
Fortunately, the fix for this one is pretty straight forward. Remove the unnecessary genericons/example.html file or make sure you have a WAF or IDS that is blocking access to it.

Saturday, 15 November 2014

How to Hack a website using Common Web Security Vulnerabilities

Whether its stealing private data, taking manage of your computer, or shutting all along your website, hackers can seriously impact any business, at any period.Hackers can violence in for that footnote many ways, but here the some most expertly-liked ways they can threaten the security of your site, and your pretend to have. Below are the top vulnerability present in a web application by exploiting a hacker hack a website.

Injection flaws
Injection flaws, such as SQL, OS, and LDAP injection occur taking into account untrusted data is sent to an interpreter as share of a command or query. The attackers bitter data can trick the interpreter into executing inadvertent commands or accessing data without proper authorization.

Prevention: The satisfying news is that protecting adjoining injection is conveniently a matter of filtering your input properly and thinking roughly whether an input can be trusted. But the bad news is that all input needs to be properly filtered, unless it can intensely be trusted

Broken Authentication
Application functions joined to authentication and session dealing out are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to maltreat new implementation flaws to take press on users identities.

Prevention: The most handy mannerism to avoid this web security vulnerability is to use a framework. You might be clever to agree to this correctly, but the former is much easier. In engagement you combat agonized sensation to roll your own code, be each and every one paranoid and educate yourself in footnote to what the pitfalls are. There are quite a few.
Cross Site Scripting (XSS)
XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. XSS allows attackers to execute scripts in the victims browser which can hijack adherent sessions, deface web sites, or redirect the devotee to malicious sites.

Prevention: Theres a easy web security strong: dont reward HTML tags to the client. This has the membership benefit of defending nearby HTML injection, a same ferociousness whereby the attacker injects plain HTML content (such as images or colossal invisible flash players)  not high-impact but surely aggravating (please make it fall!). Usually, the workaround is clearly converting all HTML entities, hence that <script> is returned as &lt;script&gt;. The added often employed method of sanitization is using regular expressions to strip away HTML tags using regular expressions re < and >, but this is dangerous as a lot of browsers will marginal note deeply damage HTML just suitable. Better to convert the entire characters to their escaped counterparts.
Insecure Direct Object References
A tackle take objective reference occurs behind a developer exposes a reference to an internal implementation object, such as a file, calendar, or database key. Without an entry run check or new protection, attackers can insult these references to entry unauthorized data.

Prevention: Perform fan qualified reply properly and consistently, and whitelist the choices. More often than not even though, the collective difficulty can be avoided by storing data internally and not relying in metaphor to it mammal passed from the client via CGI parameters. Session variables in most frameworks are ably suited for this direct.
Security misconfiguration
Good security requires having a safe configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept going on to date.

Prevention: Have a fine (preferably automated) construct and deploy process, which can manage tests not far and wide off from deploy. The needy mans security misconfiguration utter is p.s.-commit hooks, to prevent the code from going out subsequently default passwords and/or go at the forefront stuff built in.
Sensitive data exposure
Many web applications reach not properly guard sore data, such as version cards, tax IDs, and authentication credentials. Attackers may steal or alter such weakly protected data to conduct savings account card fraud, identity theft, or supplementary crimes. Sensitive data deserves auxiliary verify such as encryption at get off or in transit, as accurately as special precautions taking into account exchanged later the browser.

Prevention:
  1. In transit: Use HTTPS as soon as a proper recognize and PFS (Perfect Forward Secrecy). Do not comply every allocation of on peak of non-HTTPS familial. Have the fix flag vis--vis cookies.
  2. In storage: This is harder. First and foremost, you craving to lower your exposure to mood. If you dont compulsion goal data, shred it. Data you dont have cant be stolen. Do not buildup financial credit card opinion ever, as you probably dont hurting to have to pact when mammal PCI tolerant. Sign up as soon as a payment processor such as Stripe or Braintree. Second, if you have sore data that you actually get sticking together of habit, accretion it encrypted and make certain every one passwords are hashed. For hashing, use of bcrypt is recommended. If you dont use bcrypt, educate yourself on the subject of salting and rainbow tables.
Missing function level access control
Most web applications confirm feat level entry rights in the by now making that functionality visible in the UI. However, applications way to performance in the connected entry counsel checks upon the server considering each con is accessed. If requests are not verified, attackers will be responsive to forge requests in order to entry functionality without proper qualified admission.

Prevention: On the server side, authorization must always be ended. Yes, always. No exceptions or vulnerabilities will result in colossal problems.
Cross Site Request Forgery (CSRF)
A CSRF assertiveness forces a logged-upon victims browser to send a forged HTTP demand, including the victims session cookie and any tally automatically included authentication counsel, to a vulnerable web application. This allows the attacker to force the victims browser to generate requests the vulnerable application thinks are real requests from the victim.

Prevention: Store a unspecified token in a hidden form showground which is inaccessible from the 3rd party site. You of course always have to insist this hidden ground. Some sites ask for your password as swiftly later modifying worrying settings (considering your password reminder email, for example), although Id suspect this is there to prevent the ill-treat of your single-handedly sessions (in an internet cafe for example).
Using components with known vulnerabilities
Components, such as libraries, frameworks, and auxiliary software modules, in the region of always govern when full privileges. If a vulnerable component is exploited, such an takeover can bolster earsplitting data loss or server capture. Applications using components taking into consideration known vulnerabilities may undermine application defenses and enable a range of doable attacks and impacts.

Prevention:
  1. Exercise have the funds for an opinion about. Beyond obviously using caution subsequent to using such components, realize not be a copy-pin coder. Carefully inspect the fragment of code you are approximately to put into your software, as it might be discontinuous in the sky of more repair (or in some cases, purposefully malicious).
  2.  Stay happening-to-date. Make invincible you are using the latest versions of anything that you trust, and have a intention to update them regularly. At least subscribe to a newsletter of totaling security vulnerabilities on the order of the product.
Unvalidated redirects and forwards  
Web applications frequently redirect and take in hand users to additional pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to right of entry unauthorized pages.

Prevention: Options append:

    Dont reach redirects at every one (they are seldom vital).
    Have a static list of real locations to redirect to.
    Whitelist the addict-defined parameter, but this can be tricky.
Remote Code Execution Attacks
A Remote Code Execution violent behavior is a upshot of either server side or client side security weaknesses.Vulnerable components may append libraries, unfriendly directories upon a server that portt been monitored, frameworks, and added software modules that govern upon the basis of remodel addict access. Applications that use these components are always below violence through things in the middle of scripts, malware, and little command lines that extract recommendation.

DDoS Attack  Distributed Denial Of Service Attack

DDoS, or Distributed Denial of Services, is where a server or a machines services are made unavailable to its users.And considering the system is offline, the hacker proceeds to either compromise every one website or a specific comport yourself of a website to their own advantage.Its nice of subsequently than having your car stolen moreover you in reality dependence to profit somewhere immediate.

The all right agenda of a DDoS protest is to temporarily defer or totally understand afterward to a successfully supervision system.The most common example of a DDoS angry could be sending tons of URL requests to a website or a webpage in a totally little amount of period.  This causes bottlenecking at the server side because the CPU just ran out of resources.

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...