Security Testing

Thursday, July 5, 2018

Validation Rule

You can add input validation to Web Forms pages by using validation controls.
To make sure that all the required parameters exist in a request, use the "RequiredFieldValidator" validation control. This control ensures that the user does not skip an entry in the web form.
To make sure user input contains only valid values, you can use one of the following validation controls:
[1] "RangeValidator": checks boundary value in between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates.

[2] "RegularExpressionValidator": checks that the entry matches a pattern defined by a regular expression. Validation allows to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on.



Session Hijacking Attack and Prevention

Session Hijacking:-
It is also known as TCP hijacking or cookie hijacking obtaining a session ID over the network. Once a session has been accessed the attacker that do anything as an authorized user. Session ID is normally stored in cookie and URL.
There are four main methods used to perpetrate a session hijack
Session Fixation, Attacker sending the email with a link that contains a particular session id. The attacker now only has to wait until the user logs in.
Session side-jacking, an attacker uses packet sniffing to read network traffic between two parties to steal the session cookie. Websites use SSL encryption for login pages to prevent attackers from seeing the password, but do not use encryption for the rest of the site once authenticated.

Cross-site Scripting, capture victim’s Session ID using XSS attack by using javascript.

Malware and unwanted programs can use browser hijacking to steal a browser's cookie files without a user's knowledge.


Prevent session hijacking
Encryption of the data traffic passed between the parties by using SSL/TSL
Use of a long random number or string as the session key. This reduces the risk that an attacker could not simply guess the session ID.
Regenerating the session id after a successful login. This prevents session fixation because the attacker does not know the session id of the user after s/he has logged in.
Some services change the value of the cookie with each and every request. This reduces the attacker impact.

The way to prevent session hijacking is enabling protection from client side. Most Time session hijacks from the client side. The users should have an efficient antivirus, anti-malware software, and should keep the software up to date.

Condition of cross site scripting and solution

XSS:- It doesn't need an authenticated session and can be exploited when the vulnerable website doesn't do the basic validation or escaping input. Invulnerable website attacker sends text-based attack script that effects the application. Attacker XSS attack starts with simple HTML tag in the of a regular expression.
                                   The attacker injects the value in URL or Textbox. They run our script on the vulnerable website. The website reflects the error message through pop up.
Three type of XSS

Stored XSS Attack:- In the attacker inject the script and script stored permanently on the target server.

Reflected XSS Attack:- In this attacker inject the script and website thrown the error message.


DOM XSS Attack:- It generally involved in server site controller, script sent to the client but not sanitize.

Megitation:- 1. Understand all the potential areas where untrusted input inject

2. Specify character encoding like UFT-8

3. Input validation. Transform hazardous character into a character

Viewstate user key & Double submit cookie

CSRF Attack protection to all pages that inherit from the site.master page.
1. All web form pages data modification use the site.master page.
2. Al request data modification use Viewstste.
3. Website must be free from XSS vulnerabilities.

By using Microsoft . Net Protection Library
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;

}

Anti-CSRF and AJAX

The Form token is make problem for AJAX request, Ajax is send the JASON data not a HTML form because of this form token not be validated in this form. So, the solution is send the token in a custom header in HTTP. Code use Razor syntax to generate the token, and add token in AJAX request. This token is generated by calling AntiForgery.GetTokens.


string cookieToken, formToken;
    Antiery.GetTokens(null, out cookieToken, out formToken);
    var responseCookie = new HttpCookie("__AJAXAntiXsrfToken")
    {
        HttpOnly = true,
        Value = cookieToken
    };
    if(FormsAuthentication.RequireSSL && HttpContext.Current.Request.IsSecureConnection)
    {
        responseCookie.Secure = true;
    }
    HttpContext.Current.Response.Cookies.Set(responseCookie);
    return formToken;
AntiForgery.Validate method validate the tokens and throws an exception if the tokens are not valid.
void ValidateRequestHeader(HttpRequestMessage request)
{
    string cookieToken = "";
    string formToken = "";
    IEnumerable<string> tokenHeaders;
    if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
    {
        string[] tokens = tokenHeaders.First().Split(':');
        if (tokens.Length == 2)
        {
            cookieToken = tokens[0].Trim();
            formToken = tokens[1].Trim();
        }
    }
    AntiForgery.Validate(cookieToken, formToken);
}


Anti Forgery Token Prevention

Anti-Forgery Token
It is help to prevent the CSRF attack, ASP.NET MVC uses anti forgery token.
1.       The client request HTML page contain a FORM.
2.       The server include two token in the response. One tone is the cookie, second token is palce in the hidden form field. Token are randomly generated not be guessable.
3.       When client submit the form, it must send both tokens back to the server.
4.       If request does not include both token server disallow the request.
<form action=”path” method=”post”>
<input name=”_requestverificationtoken” type=”hidden”
                                Value=”fhsdvjknsdfk634754795jnskdji8yh”/>
<input type=”submit” value=”submit”/>
</form>
Due to same origin policies malicious page can’t be read the token. Because of this anti forgery token works.
IN MVC
To add the anti-forgery tokens to a Razor page, use the HtmlHelper.AntiForgeryToken helper method
@using (Html.BeginForm("Manage", "Account")) {
    @Html.AntiForgeryToken()
}

CSRF(Cross Site Request Forgery)



Defense CSRF(Cross site request forgery)
1.       Check standard header to verify the request is the same origin

a.       The origin request is coming from (Source origin)
b.      The origin request is going to (target origin)

2.       Check CSRF token
d           Validate the cookie token and form token


Configure the webSEAL to validate the referrer header incoming HTTP request