Security Testing

Thursday, July 5, 2018

Symmetric & Asymmetric Encryption

Symmetric Encryption
Symmetric encryption is the best-known technique. Use a secret key, which can be a number, word, or string of random letters, is applied on a message to change the content in a particular way. It is very simple as shifting each letter by a number of places in the alphabet. Both sender and recipient know the secret key, Secret key can encrypt and decrypt all messages.


Asymmetric Encryption
When secret keys is exchanging over the Internet might be going the wrong hands. After kept the secret key anyone decrypt the message. Solution is asymmetric encryption, in which there are two related keys--a key pair. A public key is easily available to anyone who want to send a message. A second, private key is kept secret, so that only you know it.

Encrypt message by using the public key can only be decrypt by applying the same algorithm, but by using the matching private key. If message encrypt by using the private key can only be decrypt by using the matching public key.

Potential File Upload or File Upload

User want facility to upload the file. An attacker take the privilege of this facility to upload the malicious file. It have potential to get malware attack or malicious code. Attacker is aim to execute the malicious code in website. This vulnerability is high severity level.
Attacking in a website through the upload file which contain malicious code it may create some issue:-
· System takeover could happen entirely
· Overloading of a database or a file system could occur
· Back-end systems could even become attacked by such malicious code
· Attacks against clients are also possible
· Simple defacement could be the result as well
· In fact, the effect and its hazardous aspects fundamentally vary according to the application’s reaction towards the file and the place where it stores the file essentially



There are two ways to attack file upload.
1. It involve to type of upload file. The file name is already exit it overwrite the existing file. It is generated some metadata like, path, file name which is provided by HTTP encoding. Malicious data may be overwrite the critical file or bad location. For ex, Attacker upload a file on root folder with the name of…/…//index.php.
2. Attacker can be attacked by malicious file upload involves the content of the uploaded file. The uploaded file could contain malicious code in the form of an exploit, virus, Trojan or malware, which could be used to gain control of the Web server. For example, it is possible to hide PHP code inside an image file and still have it appear to be an image. When the image is opened, it also executes the code hidden in the file.
Attacks on application platform
· Upload .jsp file into web tree - jsp code executed as the web user
· Upload .gif file to be resized - image library flaw exploited
· Upload huge files - file space denial of service
· Upload file using malicious path or name - overwrite a critical file
· Upload file containing personal data - other users access it
· Upload file containing "tags" - tags get executed as part of being "included" in a web page
· Upload .rar file to be scanned by antivirus - command executed on a server running the vulnerable antivirus software
Attacks on other systems
· Upload .exe file into web tree - victims download trojaned executable
· Upload virus infected file - victims' machines infected
· Upload .html file containing script - victim experiences Cross site scripting (XSS).
· Upload .jpg file containing a Flash object - victim experiences Cross-site Content Hijacking.
Solution
Create a white list for accepting MIMIE types. NEVER use a blacklist technique.
Can’t access though the Internet.
Define a .htaccess file that will only allow access to files with allowed extensions.
Do not place the .htaccess file in the same directory where the uploaded files will be stored.
The application should use a whitelist of allowed file types. This list determines the types of files that can be uploaded, and rejects all files that do not match approved types.
The application should use client- or server-side input validation to ensure evasion techniques have not been used to bypass the whitelist filter.
The application should set a maximum length for the file name, and a maximum size for the file itself.
The directory to which files are uploaded should be outside of the website root.
All uploaded files should be scanned by antivirus software before they are opened.

The application should not use the file name supplied by the user. Instead, the uploaded file should be renamed according to a predetermined convention.

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-jackingan 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 Scriptingcapture 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);
}