A Thesis On Preventing Cyber Attack And Other Vulnerabilities By Krishna Gehlot
V ABSTRACT If security of a web application is weak, the attackers can easily get in. It is relatively easy to compromise a site, but it takes significant resources for a defender to provide even modest security. One of the reasons for this is that current web security technologies are very complex to learn, understand, implement and maintain. As a result, security may be ignored in favour of other concerns. The web needs simpler policy which can stop basic as well as critical cyber attacks in order to level the playing field. With the rise of the Internet, web applications, such as online banking and web- based services, emails, social sites have become integral to many people’s daily lives. Web applications have brought with them new classes of computer security vulnerabilities, such as SQL injection and cross-site scripting (XSS), etc. that in recent years have exceeded previously prominent vulnerability classes, such as buffer overflows, in both reports of new vulnerabilities and reports of exploits. SQL injection and XSS are both instances of the broader class of input validation based vulnerabilities. At their core, both involve one system receiving, transforming, and constructing string values, some of which come from untrusted sources, and presenting those values to another system that interprets them as programs or program fragments. These input validation-based vulnerabilities therefore require fundamentally new techniques to characterize and mitigate them. In this thesis we are providing a vulnerability scanning and analyzing tool of various kinds of SQL injection and Cross Site Scripting (XSS) attacks. Our approach can be used with any web application not only the known ones. As well as it supports the most famous Database management servers, namely MySQL and etc.
VI List of Abbreviations XSS – Cross Side Scripting. TCP – Transmission Control Protocol. SQL – Structured Query Language. RDBMS – Relational Database Management System SQLi – Structured Query Language Improved FPD – Full Path Disclosure. CLI – Command Line Interface. HTML – Hyper Text Markup Language. CSRF – Cross-Site Request Forgery. OWASP – Open Web Application Security Project. DOS – Denial of Service
VII Contents Declaration II Certificate III Acknowledgments IV Abstract V List of Abbreviations VI Contents VII List of Figures IX List of Tables X 1 Introduction 1 1.1 Web Application Security . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 What is Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3.1 Active Attack. . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.3.2 Passive Attack. . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.4 What is Vulnerability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 2 Literature Survey 8 2.1 Web Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Web Application Vulnerability . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Most Common Security Issue . . . . . . . . . . . . . . . . . . . . . . 14 3 Proposed Work 17 3.1 Technologies Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.2 Description of proposed work . . . . . . . . . . . . . . . . . . . . . . 18 3.3 Good Programming Practice . . . . . . . . . . . . . . . . . . . . . . 48
VIII 4 Platform of Research 54 5 Conclusion and Future Work 55 Conclusion ....................................................................................................55 Future Work..........................................................................................................56 REFERENCES 57
IX List of Figures S.No Figure Description Page No 1 Figure 1.1: Distributed Denial of Service(SDoS) Attack 5 2 Figure 1.2: Spoofing Attack 5 3 Figure 1.3: Man-in-the-middle attack 6 4 Figure 1.4: Ping of Death Attack. 6 5 Figure 1.5: Pinging an IP with ping of death. 7 6 Figure 1.6: Ping Flood Attack. 7 7 Figure 1.7: Port Scanner Attack. 8 8 Figure 1.8: Idle Scan Attack. 9 9 Figure 1.9: Exploit vulnerability process diagram. 10 10 Figure 2.1: Web application system architecture 12 11 Figure 2.2: Top vulnerabilities in March 2012 13 12 Figure 3.1: Cross Side Scripting Vulnerability 22 13 Figure 3.2: SQL Injection Vulnerability. 26 14 Figure 3.3: Cross-Site Request Forgery Vulnerability. 30 15 Figure 3.4: Full Path Disclosure vulnerability. 33 16 Figure 3.5: Arbitrary Code Execution Vulnerability. 36 17 Figure 3.6: Denial of Service vulnerability. 38 18 Figure 3.7: Memory Exhaustion vulnerability. 40 19 Figure 3.8: File Inclusion vulnerability. 41
X List of Tables Relationship between New Top Ten, Last year’s top ten and WAS top vulnerabilities [1]..............................................................................................................13
CHAPTER 1. INTRODUCTION 1 Chapter 1 Introduction The increased use of internet and web applications has become an important part of our society. Web applications, web services and websites plays important role for any business. Web applications are being used almost everywhere like homes, colleges, schools, organizations, institutes, businesses etc. Generally, programmers and developers do not care about many additional configurations and connect applications to the Internet immediately. Most programmers are not technically sound to do advance programming. Due to this negligence to security of code, it motivates attackers to hack less secure web application. To improve the security of the web applications and web services this material is presented, this document is obtained from the Analysis done on Code, Audit, Network reports, Security reports of various PHP Web Applications, and other sources of NIC’s best practices. This Web Security Standards and Practices document establishes a baseline of security related requirements for all web services and websites, including branded applications supported or hosted by 3rd parties. Advances in web technologies coupled with a changing business environment, mean that web applications are becoming more prevalent in corporate, public and Government services today. Although web applications can provide convenience and efficiency, there are also a number of new security threats, which could potentially pose significant risks to an organisation‟s information technology infrastructure if not handled properly.[1][2] Web Application Firewalls (WAF). If all the security measures deployed ahead of the WAF were truly effective in protecting the application, there would be no need for a Web Application Attack Report[3]. But even with all those layers protecting the endpoint, the network, and everything in between user and application, threats still manage to sneak through to the application, proving once again that Improved Secure Sphere WAF is the last line of defense for web applications. So, until all security products are perfect, and applications can protect against all attacks, there will be a WAAR.[4]
CHAPTER 1. INTRODUCTION 2 Application Defense Center is a proud contributor of valuable cyber crime trends and shares information with the security community of customers, vendors and partners to defend better against existing and new threats. The purpose of this document is to provide coding standards, which are based on the practices, to minimize security and vulnerability exploits due to improper and non standard coding practices. It also provides references to information about common web security vulnerabilities to enhance understanding of the root causes of such issues and how to remediate, prevent or eliminate them appropriately. This document is created to focus corporations and government agencies on the most serious of these vulnerabilities. Web application security has become a hot topic as companies race to make content and services accessible though the web. At the same time, hackers are turning their attention to the common weaknesses created by application developers.[2] 1.1 Web Application Security Web application security is a branch of Information Security that deals specifically with security of websites, web applications and web services. At a high level, Web application security draws on the principles of application security but applies them specifically to Internet and Web systems. With the emergence of Web 2.0, increased information sharing through social networking and increasing business adoption of the Web as a means of doing business and delivering service, websites are often attacked directly. Hackers either seek to compromise the corporate network or the end-users accessing the website by subjecting them to drive-by downloading. As a result, industry is paying increased attention to the security of the web applications themselves in addition to the security of the underlying computer network and operating systems.[4] 1.2Overview Web applications serve a wide range of purposes, from social networking, sensitive data management to online shopping. The advent of smart mobile devices enables users to access web applications even on the go. A recent Symantec Internet security threat report states that the number of reported web vulnerabilities increased from 4,989 in 2011 to 5,291 in 2012, incurring an average cost of $591,780 for businesses [68]. Furthermore, web vulnerabilities are widespread. A WhiteHat security statistics report published in 2013 shows that 86% of all the surveyed websites had at least one serious vulnerability
CHAPTER 1. INTRODUCTION 3 during 2012, and the number of serious vulnerabilities per website was 56 on average. Recent years have witnessed the rapid growth of web applications and their code complexity. Web applications have evolved from sets of simple, static web pages, to feature-rich Web 2.0 applications which frequently integrate third-party services. Unfortunately, the more features that a modern web application possesses, the larger attack surface it often exposes to attackers. With the incorporation of client-side JavaScript code, attackers can inject malicious JavaScript code in user inputs and exploit various ways that web browsers invoke their JavaScript engines. In cases where web applications behave differently to administrators and normal users, attackers can break authentication processes and access sensitive information and functionality. In recent years, the integration of third-party services has become popular, giving attackers a new opportunity to exploit miscommunications between servers and service providers. The best practice for web security is to build an application with security in mind end-to-end. However, many web developers are unfamiliar with various attack vectors, especially application-specific ones. Application- specific vulnerabilities in web applications are especially challenging to detect. When building an application, developers often have a clear picture of what the ideal application should be in their minds. Unfortunately, in practice, the implemented application often does more than what is intended. Put it another way, unexpected user inputs and logic flows can allow attackers to abuse implemented but insufficiently guarded application-specific functionality in dangerous ways. The uniqueness and complexity of logic flows complicate the establishment of a general line of defense against application-specific attacks. This dissertation focuses on detecting crucial, ungrounded assumptions that web developers make about user inputs and logic flows in web applications. While existing solutions mainly focus on vulnerabilities related to untrusted user inputs, the key observation of this dissertation is that it is also important to validate critical assumptions on logic flows which are application-specific. Less traveled paths in web applications may indeed lead to fruitful attacks. Inferring and enforcing such implicit assumptions on logic flows are vital yet challenging for web application security[5]. 1.3What is Attack In computer and computer networks an attack is any attempt to destroy, expose, alter, disable, steal or gain unauthorized access to or make unauthorized use of an asset. an assault on system security that derives from an intelligent threat, i.e., an intelligent act that is a deliberate attempt (especially in the sense of a method or technique) to evade security services and violate the security policy of a system. An attack, via cyberspace, targeting an enterprise’s use of
CHAPTER 1. INTRODUCTION 4 cyberspace for the purpose of disrupting, disabling, destroying, or maliciously controlling a computing environment/infrastructure; or destroying the integrity of the data or stealing controlled information.[1] An attack can be can be further classified into two parts: 1. Active 2. Passive. 1.3.1 Active Attack An "active attack" attempts to alter system resources or affect their operation. The following is a partial short list of active attacks: 1. Denial-of-service attack 2. Spoofing 3. Man in the middle 4. Ping flood 5. Ping of death 1.3.1.1 Denial-of-Service Attack Denial-of-Service attack (DoS attack) is a cyber-attack where the perpetrator seeks to make a machine or network resource unavailable to its intended users by temporarily or indefinitely disrupting services of a host connected to the Internet. Denial of service is typically accomplished by flooding the targeted machine or resource with superfluous requests in an attempt to overload systems and prevent some or all legitimate requests from being fulfilled.[1]
CHAPTER 1. INTRODUCTION 5 Figure 1.1: Distributed Denial of Service(SDoS) Attack.[1] 1.3.1.2 Spoofing Attack Spoofing attack is a situation in which one person or program successfully masquerades as another by falsifying data, thereby gaining an illegitimate advantage.[1] Figure 1.2: Spoofing Attack.[1]
CHAPTER 1. INTRODUCTION 6 1.3.1.3 Man-in-the-middle Attack Man-in-the-middle attack (MITM, sometimes called a "bucket brigade attack") is an attack where the attacker secretly relays and possibly alters the communication between two parties who believe they are directly communicating with each other.[1][2] Figure 1.3: Man-in-the-middle attack. 1.3.1.4 Ping of Death Attack A ping of death is a type of attack on a computer system that involves sending a malformed or otherwise malicious ping to a computer.[1] Figure 1.4: Ping of Death Attack.[1]
CHAPTER 1. INTRODUCTION 7 Figure 1.5: Pinging an IP with ping of death.[1] 1.3.1.5 Ping flood Attack A ping flood is a simple denial-of-service attack where the attacker overwhelms the victim with the flood option of ping which sends ICMP packets as fast as possible without waiting for replies.[1] Figure 1.6:Ping Flood Attack.[1] 1.3.2 Passive Attack
CHAPTER 1. INTRODUCTION 8 A "passive attack" attempts to learn or make use of information from the system but does not affect system resources.[1] The following is a partial short list of passive attacks: 1. Wiretapping 2. Port scan 3. Idle scan 1.3.2.1 Telephone tapping (Wiretapping) Telephone tapping is the monitoring of telephone and Internet conversations by a third party, often by covert means. The wire tap received its name because, historically, the monitoring connection was an actual electrical tap on the telephone line. Legal wiretapping by a government agency is also called lawful interception. Passive wiretapping monitors or records the traffic.[1] 1.3.2.2 Port Scanner Port scanner is an application designed to probe a server or host for open ports. This is often used by administrators to verify security policies of their networks and by attackers to identify network services running on a host and exploit vulnerabilities. Figure 1.7: Port Scanner Attack. 1.3.2.3 Idle Scan The idle scan is a TCP port scan method that consists of sending spoofed packets to a computer to find out what services are available. This is accomplished by impersonating another computer called a "zombie" (that is not transmitting or receiving information) and observing the behavior of the
CHAPTER 1. INTRODUCTION 9 ''zombie'' system. Figure 1.8: Idle Scan Attack. 1.4What is Vulnerability In computer security, a vulnerability is a weakness which allows an attacker to reduce a system's information assurance. Vulnerability is the intersection of three elements: a system susceptibility or flaw, attacker access to the flaw, and attacker capability to exploit the flaw.[1] To exploit a vulnerability, an attacker must have at least one applicable tool or technique that can connect to a system weakness. In this frame, vulnerability is also known as the attack surface. Figure 1.9 is showing vulnerability process diagram.
CHAPTER 1. INTRODUCTION 10 Figure 1.9: Exploit vulnerability process diagram. A threat agent through an attack vector exploits a weakness (vulnerability) of the system and the related security controls, causing a technical impact on an IT resource (asset) connected to a business impact.[2]
CHAPTER 2. LITERATURE SURVEY 11 Chapter 2 Literature Survey This thesis aims to advance the security against web security attacks by using some prevention techniques each of which is capable to hijack the entire system or web application. So for the guarantee of security of a web application we choose to build exploit prevention techniques for their low security performance overhead and the ease of adoption, i.e., more practical. But comparing to existing prevention techniques, our solutions are based on basic security principles so they are able to completely block one type of exploit technique and withstand the rapidly evolving arm race from offensive technologies. 2.1 Web Applications Web applications enable much of today’s online business including banking, shopping, university admissions, email, social networking, and various governmental activities. They have become ubiquitous because users only need a web browser and an Internet connection to receive a system-independent interface to some dynamically generated content. The data web that applications handle, such as credit card numbers and product inventory data, typically has significant value both to the users and to the service providers. Additionally, users care that web pages behave as trusted servers intend because web browsers run on users’ local systems and often have bugs that could be exploited by maliciously written pages.[3]
CHAPTER 2. LITERATURE SURVEY 12 Figure 2.1: Web application system architecture. Figure 1.1 shows typical system architecture for web applications. This three-tiered architecture consists of a web browser, which functions as the user interface; a web application server, which manages the business logic; and a database server, which manages the persistent data 2.2 Web Application Vulnerabilities so far The majority of web application attacks occur through cross-site scripting (XSS) and SQL injection attacks which typically result from flawed coding, and failure to sanitize input to and output from the web application. These are ranked in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors. Phishing is another common threat to the Web application and global losses from this type of attack in 2012 were estimated at $1.5 billion. According to the security vendor Cenzic, the top vulnerabilities in March 2016 include following vulnerabilities showing in figure:
CHAPTER 2. LITERATURE SURVEY 13 Figure 2.2: top vulnerabilities in March 2012. [1] The table below highlights the relationship between the new Top Ten, last year’s Top Ten, and the WAS TC Thesaurus. New Top Ten 2007 Top Ten 2006 New WAS Thesaurus A1 Unvalidated Input A1 Unvalidated Parameters Input Validation A2 Broken Access Control A2 Broken Access Control Access Control A3 Broken Authentication and Session Management A3 Broken Account and Session Management Authentication and Session Management A4 Cross Site Scripting (XSS) Flaws A4 Cross Site Scripting (XSS) Flaws Input Validation->Cross site scripting A5 Buffer Overflows A5 Buffer Overflows Buffer Overflows A6 Injection Flaws A6 Command Injection Flaws Input Validation- >Injection A7 Improper Error Handling A7 Error Handling Problems Error Handling A8 Insecure Storage A8 Insecure Use of Data Protection
CHAPTER 2. LITERATURE SURVEY 14 Cryptography A9 Denial of Service N/A Availability A10 Insecure Configuration Management A10 Web and Application Server Misconfiguration Application Configuration Management Infrastructure Configuration Management 2.3 Most Common Security Issues and Vulnerabilities The following is a short summary of the most significant web application security vulnerabilities. Each of these is described in more detail in the following next chapter. 2.3.1 Broken Authentication and Session Management The potential threat here is that attackers might compromise passwords, keys, or authentication tokens in order to assume the identity of other users. Authentication functions in a web application are not deployed precisely that gives hacker privilege to steal information like session tokens, passwords, keys etc. This flaw is caused when account credentials and session tokens are not properly protected.[1][5] 2.3.2 SQL Injection (SQLi) SQL Injection (SQLi) refers to an injection attack wherein an attacker can execute malicious SQL statements (also commonly referred to as a malicious payload) that control a web application’s database server (also commonly referred to as a Relational Database Management System – RDBMS). Since an SQL Injection vulnerability could possibly affect any website or web application that makes use of an SQL-based database, the vulnerability is one of the oldest, most prevalent and most dangerous of web application vulnerabilities.[5] 2.3.3 Cross-site Scripting In this security issue web application takes unreliable data and revert it back to the web browser. The potential threat of XSS is allowing the execution of scripts in the victim's browser that could hijack user sessions, deface websites, and possibly introduce worms, redirect to malicious URL,
CHAPTER 2. LITERATURE SURVEY 15 deface websites etc. This flaw is caused by the improper validation of user- supplied data when an application takes that data and sends it to a web browser without first validating or encrypting the content.[5] 2.3.4 Cross-site request forgery Hackers can create malicious web pages which produce fake requests that are almost like real ones and forces and user to perform un- desirable acts on a web application in which they are currently logged in. If CSRF attack is successful, it can force the end user to execute state changing requests like changing their email address, transferring funds etc. If the victim is an administrative account, CSRF can compromise the entire web application. CSRF takes benefit of the fact that most web applications permit hackers to guess all the information of a particular individual.[5] 2.3.5 Full Path Disclosure (FPD) Full Path Disclosure (FPD) is the revelation of the full operating path of a vulnerable script. The FPD bug is executed by injecting unexpected characters into certain parameters of a web-page. The script doesn't expect the injected character and returns an error message that includes information of the error, as well as the operating path of the targeted script. The attackers can use this weakness to steal sensitive data, or conduct more serious attacks. Applications can unintentionally leak information.[5] 2.3.6 Arbitrary Code Execution Arbitrary code execution is a program that is designed to exploit such vulnerability that it allows web application to execute Arbitrary code is called an arbitrary code execution exploit. Most of these vulnerabilities allow the execution of machine code and most exploits therefore inject and execute shell code to give an attacker an easy way to manually run arbitrary commands.[1] 2.3.7 Denial-of-service attack Denial-of-service attack In computing, a denial-of-service attack (DoS attack) is a cyber-attack where the perpetrator seeks to make a machine or network resource unavailable to its intended users by temporarily or indefinitely disrupting services of a host connected to the Internet.[1] 2.3.8 Memory corruption Memory corruption occurs in a computer program when the
CHAPTER 2. LITERATURE SURVEY 16 contents of a memory location are unintentionally modified due to programming errors; this is termed violating memory safety. When the corrupted memory contents are used later in that program, it leads either to program crash or to strange and bizarre program behavior. Nearly 10% of application crashes on Windows systems are due to heap corruption.[1] 2.3.9 HTML Injection HTML Injection: It is a sort of injection attack that happens when an end user has the power to control an input point and is capable of injecting random HTML code into an unprotected web page. This type attack is used to steal user’s cookie, modify web page for malicious purpose etc.[1]
CHAPTER 3. PROPOSED WORK 17 Chapter 3 Proposed Work The challenge of identifying the web application vulnerabilities is a virtually impossible task. There is not even widespread agreement on exactly what is included in the term ―web application security.‖ Some have argued that we should focus only on security issues that affect developers writing custom web application code. Others have argued for a more expansive definition that covers the entire application layer, including libraries, server configuration, and application layer protocols. In the hopes of addressing the most serious risks facing organizations, This document give a relatively broad interpretation to web application security, while still keeping clear of network and infrastructure security issues. Another challenge to this effort is that each specific vulnerability is unique to a particular organization‘s website. There would be little point in calling out specific vulnerabilities in the web applications of individual organizations, especially since they are hopefully fixed soon after a large audience knows of their existence. Therefore, in this thesis we have chosen to focus on the top classes, types, or categories of web application vulnerabilities. 3.1Technologies Used To fix various vulnerabilities we are working on following technologies and support : 1. PHP 2. Mysqli 3.1.1 PHP
CHAPTER 3. PROPOSED WORK 18 PHP is a server-side scripting language designed primarily for web development but also used as a general-purpose programming language. PHP code may be embedded into HTML or HTML5 markup, or it can be used in combination with various web template systems, web content management systems and web frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the web server or as a Common Gateway Interface (CGI) executable. The web server software combines the results of the interpreted and executed PHP code, which may be any type of data, including images, with the generated web page. PHP code may also be executed with a command-line interface (CLI) and can be used to implement standalone graphical applications. 3.1.2Mysqli The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP programming language to provide an interface with MySQL databases. There are three main API options when considering connecting to a MySQL database server: PHP's MySQL Extension. PHP's MySQLi Extension. PHP Data Objects (PDO) The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which, (according to the PHP website) are:  An object oriented interface  Support for prepared statements  Support for multiple statements  Support for transactions  Enhanced debugging support  Embedded server support  More powerful Functionality 3.2 Description of Proposed work Various vulnerabilities along with their definition, impact, example and protection methods will be discussed with their Symptom as below. 3.2.1 Vulnerability - Broken authentication and session management:
CHAPTER 3. PROPOSED WORK 19 3.2.1.1 Explanation Broken authentication and session management is related to access control, sometimes called authorization, is how a web application grants access to content and functions to some users and not others. These checks are performed after authentication, and govern what ‗authorized‘ users are allowed to do. Access control sounds like a simple problem but is insidiously difficult to implement correctly. A web application‘s access control model is closely tied to the content and functions that the site provides. In addition, the users may fall into a number of groups or roles with different abilities or privileges.[5] 3.2.1.2 Impact on Web Application All known web servers, application servers, and web application environments are susceptible this issues. Even if a site is completely static, if authentication is not implemented properly, hackers could gain access to sensitive files and deface the site, or perform other mischief. 3.2.1.3 Detection of vulnerability Both code review and penetration testing can be used to diagnose broken authentication and session management problems. 3.2.1.4 Recommendation Defining and documenting your site‘s policy with respect to securely managing users credentials is a good first step. Ensuring that your implementation consistently enforces this policy is key to having a secure and robust authentication and session management mechanism. Some critical areas include:  Password Strength - passwords should have restrictions that require a minimum size and complexity for the password. Complexity typically requires the use of minimum combinations of alphabetic, numeric, and/or non-alphanumeric characters in a user‘s password (e.g., at least one of each). Users should be required to change their password periodically. Users should be prevented from reusing previous passwords.  Password Use - Users should be restricted to a defined number of login attempts per unit of time and repeated failed login attempts should be logged. Passwords provided during failed login attempts should not be recorded, as this may expose a user‘s password to whoever can gain access to this log. The system should not indicate whether it was the
CHAPTER 3. PROPOSED WORK 20 username or password that was wrong if a login attempt fails. Users should be informed of the date/time of their last successful login and the number of failed access attempts to their account since that time.  Password Change Controls - A single password change mechanism should be used wherever users are allowed to change a password, regardless of the situation. Users should always be required to provide both their old and new password when changing their password (like all account information). If forgotten passwords are emailed to users, the system should require the user to re-authenticate whenever the user is changing their e-mail address, otherwise an attacker who temporarily has access to their session (e.g., by walking up to their computer while they are logged in) can simply change their e-mail address and request a ‗forgotten‘ password be mailed to them.  Password Storage - All passwords must be stored in either hashed or encrypted form to protect them from exposure, regardless of where they are stored. Hashed form is preferred since it is not reversible. Encryption should be used when the plaintext password is needed, such as when using the password to login to another system. Passwords should never be hardcoded in any source code. Decryption keys must be strongly protected to ensure that they cannot be grabbed and used to decrypt the password file.  Protecting Credentials in Transit - The only effective technique is to encrypt the entire login transaction using something like SSL. Simple transformations of the password such as hashing it on the client prior to transmission provide little protection as the hashed version can simply be intercepted and retransmitted even though the actual plaintext password might not be known.  Session ID Protection – Ideally, a user‘s entire session should be protected via SSL. If this is done, then the session ID (e.g., session cookie) cannot be grabbed off the network, which is the biggest risk of exposure for a session ID. If SSL is not viable for performance or other reasons then session IDs themselves must be protected in other ways. First, they should never be included in the URL as they can be cached by the browser, sent in the referrer header, or accidentally forwarded to a ‗friend‘. Session IDs should be long, complicated, random numbers that cannot be easily guessed. Session IDs can also be changed frequently
CHAPTER 3. PROPOSED WORK 21 during a session to reduce how long a session ID is valid. Session IDs must be changed when switching to SSL, authenticating, or other major transitions. Session IDs chosen by a user should never be accepted.  Account Lists - Systems should be designed to avoid allowing users to gain access to a list of the account names on the site. If lists of users must be presented, it is recommended that some form of pseudonym (screen name) that maps to the actual account be listed instead. That way, the pseudonym can‘t be used during a login attempt or some other hack that goes after a user‘s account.  Browser Caching – Authentication and session data should never be submitted as part of a GET, POST should always be used instead. Authentication pages should be marked with all varieties of the no cache tag to prevent someone from using the back button in a user‘s browser to backup to the login page and resubmit the previously typed in credentials. Many browsers now support the AUTOCOMPLETE=OFF flag to prevent storing of credentials in autocomplete caches.  Trust Relationships – Your site architecture should avoid implicit trust between components whenever possible. Each component should authenticate itself to any other component it is interacting with unless there is a strong reason not to (such as performance or lack of a usable mechanism). If trust relationships are required, strong procedural and architecture mechanisms should be in place to ensure that such trust cannot be abused as the site architecture evolves over time.[6] 3.2.2 Vulnerability - Cross-site scripting : 3.2.2.1 Explanation Cross-site scripting (XSS) vulnerabilities occur when an attacker uses a web application to send malicious code, generally in the form of a script, to a different end user. These flaws are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating it. An attacker can use cross site scripting to send 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
CHAPTER 3. PROPOSED WORK 22 tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page.[5] XSS attacks can generally be categorized into two categories:  Stored: Stored attacks are those where the injected code 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.  Reflected: Reflected attacks are those where the injected code is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web server. When a user is tricked into clicking on a malicious link or submitting a specially crafted form, the injected code travels to the vulnerable web server, which reflects the attack back to the user‘s browser. The browser then executes the code because it came from a ‗trusted‘ server. 3.2.2.2 Impact on Web Application All known web servers, application servers, and web application environments are susceptible to at XSS. Even if a site is completely static, if it is not protected properly, hackers could gain access to sensitive files and deface the site, or perform other mischief.[5] 3.2.2.3 Example
CHAPTER 3. PROPOSED WORK 23 Figure 3.1: Cross Side Scripting Vulnerability Above Figure showing that malicious code is entered into the text box, which allow program to return all company name as result to the attacker. 3.2.2.4 Detection of vulnerability XSS flaws can be difficult to identify and remove from a web application. The best way to find flaws is to perform a security review of the code and search for all places where input from an HTTP request could possibly make its way into the HTML output. Note that a variety of different HTML tags can be used to transmit a malicious JavaScript. Nessus, Nikto, and some other available tools can help scan a website for these flaws, but can only scratch the surface. If one part of a website is vulnerable, there is a high likelihood that there are other problems as well.[6] 3.2.2.5 Recommendations: Since XSS vulnerabilities occur when an application includes malicious data in its output, one logical approach is to validate data immediately before it leaves the application. However, because web applications often have complex and intricate code for generating dynamic content, this method is prone to errors of omission (missing validation). An effective way to mitigate this risk is to also perform input validation for XSS. Web applications must validate their input to prevent other vulnerabilities, such as SQL injection, so augmenting an application's existing input validation mechanism to include checks for XSS is generally relatively easy.[1] The most secure approach to validation for XSS is to create a whitelist of safe characters that are allowed to appear in HTTP content and accept input composed exclusively of characters in the approved set. For example, a valid username might only include alpha-numeric characters or a phone number might only include digits 0-9 A more flexible, but less secure approach is known as blacklisting. In which selectively rejects or escapes potentially dangerous characters before using the input. In order to form such a list, you first need to understand the set of characters that hold special meaning for web browsers.[6]
CHAPTER 3. PROPOSED WORK 24 In the content of a block-level element (in the middle of a paragraph of text):  "<" is special because it introduces a tag.  "&" is special because it introduces a character entity.  ">" is special because some browsers treat it as special, on the assumption that the author of the page intended to include an opening "<", but omitted it in error.  In attribute values enclosed with double quotes, the double quotes are special because they mark the end of the attribute value.  In attribute values enclosed with single quote, the single quotes are special because they mark the end of the attribute value.  In attribute values without any quotes, white-space characters, such as space and tab, are special.  "&" is special when used with certain attributes, because it introduces a character entity.  Non-ASCII characters (that is, everything above 128 in the ISO-8859- 1 encoding) are not allowed in URLs, so they are considered to be special in this context.  The "%" symbol must be filtered from input anywhere parameters encoded with HTTP escape sequences are decoded by server-side code. For example, "%" must be filtered if input such as "%68%65%6C%6C%6F" becomes "hello" when it appears on the web page in question.  Within the body of a <SCRIPT> </SCRIPT>:  The semicolon, parenthesis, curly braces, and new line should be filtered in situations where text could be inserted directly into a pre- existing script tag. [5] Example: <?php $string = "A 'heading' is <u>underlined</u>"; // Outputs: A 'heading' is &lt;u&gt;underlined&lt;/u&gt; echo htmlentities($string); // Outputs: A &#039;heading&#039; is &lt;u&gt;underlined&lt;/u&gt;gt; echo htmlentities($str, ENT_QUOTES); ?>
CHAPTER 3. PROPOSED WORK 25 3.2.3 Vulnerability - SQL Injection: 3.2.3.1 Explanation: Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. Attackers trick the interpreter into executing unintended commands via supplying specially crafted data. Injection flaws allow attackers to create, read, update, or delete any arbitrary data available to the application. In the worst case scenario, these flaws allow an attacker to completely compromise the application and the underlying systems, even bypassing deeply nested firewalled environments.SQL Injection (SQLi) is an attack that exploits a security vulnerability occurring in the database layer of an application (such as queries). Using SQL injection, the attacker can extract or manipulate the web application‘s data. The attack is viable when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed, and there by unexpectedly executed.[5] SQL injection errors occur when: 1. Data enters a program from an untrusted source. 2. The data is used to dynamically construct a SQL query. 3.2.3.2 Impact on Web Application Only pure static then only it is safe from SQL Injection flaws. Other than that all web application frameworks that use sql, mysql and other sql product as database or invoke sql database and fuctions are vulnerable to SQL injection attacks. This includes any components of the framework that might use back- end interpreters. SQL Injection can be caused to disclose some critical information stored in Database. Sharing the critical information can be cause to disaster. 3.2.3.3 Example Example 1: The following code dynamically constructs and executes a SQL query that searches for login detail matching a specified username. The query restricts the login detail displayed to those where the loginuser matches the user name of the currently-authenticated user. <?php $userName = $_SESSION['userName']; $password = $_POST['password']; $query = "SELECT * FROM login WHERE password = '$password ' AND
CHAPTER 3. PROPOSED WORK 26 loginuser = '$userName' "; $result = mysql_query($query); The query that this code intends to execute follows: SELECT * FROM login WHERE password = < password > AND loginuser = <userName> ; ?> Figure 3.2: SQL Injection Vulnerability. However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name 9929913899 enters the string "9929913899' OR 1=1" for User Name and password for password, then the query becomes the following: SELECT * FROM login WHERE password = 'password' AND loginuser = '9929913899' or 1=1 ; The addition of the OR '1=1' condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query: SELECT * FROM login; This simplification of the query allows the attacker to bypass the requirement that the query only return items owned by the authenticated user; the query now returns all entries stored in the login table, regardless of their specified owner, which contain username and password of all login that should
CHAPTER 3. PROPOSED WORK 27 not happen. 3.2.3.4 Detection of vulnerability However, there are many ways around to find out if our web application is infected through SQL Injection vulnerability. Online tools can identify if system is vulnerable. Deep Penetration testing can be used to identify and diagnose SQL Injection vulnerability. Stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks. 3.2.3.5 Recommendations: When a SQL query is constructed, the programmer knows what should be interpreted as part of the command and what should be interpreted as data. Parameterized SQL statements can enforce this behavior by disallowing data- directed context changes and preventing nearly all SQL injection attacks. Protection from SQL Injection can be done by using two techniques  Input validation. Use a standard input validation mechanism to validate all input data for length, type, syntax, and business rules before accepting the data to be displayed or stored. Use an "accept known good" validation strategy. Reject invalid input rather than attempting to sanitize potentially hostile data. Do not forget that error messages might also include invalid data.  Use strongly typed parameterized query APIs with placeholder substitution markers, even when calling stored procedures  Enforce least privilege when connecting to databases and other backend systems  Avoid detailed error messages that are useful to an attacker  Use stored procedures since they are generally safe from SQL Injection. However, be careful as they can be injectable (such as via the use of exec() or concatenating arguments within the stored procedure)  Do not use dynamic query interfaces (such as mysql_query() or similar)
CHAPTER 3. PROPOSED WORK 28  Do not use simple escaping functions, such as PHP‘s addslashes() or character replacement functions like str_replace("‘", "‘‘"). These are weak and have been successfully exploited by attackers. For PHP, use mysql_real_escape_string() if using MySQL, or preferably use PDO which does not require escaping.When using simple escape mechanisms, note that simple escaping functions  Cannot escape table names! Table names must be legal SQL, and thus are completely unsuitable for user supplied input.  Watch out for canonicalization errors. Inputs must be decoded and canonicalized to the application‘s current internal representation before being validated. Make sure that your application does not decode the same input twice. Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they have been checked When connecting to MySQL, the previous example can be rewritten to use parameterized SQL statements (instead of concatenating user supplied strings) as follows: <?php $mysqli = new mysqli($host,$dbuser, $dbpass, $db); $userName = $_SESSION['userName']; $itemName = $_POST['itemName']; $query = "SELECT * FROM login WHERE loginuser = ? AND password = ?"; $stmt = $mysqli->prepare($query); $stmt->bind_param('ss',$username,$password); $stmt->execute(); ?> The MySQL Improved extension (mysqli) is available for PHP5 users of MySQL. Code that relies on a different database should check for similar extensions. 3.2.4 Vulnerability - Cross-Site Request Forgery 3.2.4.1 Explanation: Cross site request forgery is not a new attack, but is simple and devastating. A CSRF attack forces a logged-on victim‘s browser to send a request to a vulnerable web application, which then performs the chosen action on behalf of the victim.
CHAPTER 3. PROPOSED WORK 29 This vulnerability is extremely widespread, as any web application that  Has no authorization checks for vulnerable actions  Will process an action if a default login is able to be given in the request (eg. http://www.example.com/admin/doSomething.php?user=admin&pa ss wd=admin)  Authorizes requests based only on credentials that are automatically submitted such as the session cookie if currently logged into the application, or ―Remember me‖ functionality if not logged into the application, or a Kerberos token if part of an Intranet participating in integrated logon with Active Directory is at risk. Unfortunately, today, most web applications rely solely on automatically submitted credentials such as session cookies, basic authentication credentials, source IP addresses, SSL certificates, or Windows domain credentials. This vulnerability is also known by several other names including Session Riding, One-Click Attacks, Cross Site Reference Forgery, Hostile Linking, and Automation Attack. The acronym XSRF is also frequently used. OWASP and MITRE have both standardized on the term Cross Site Request Forgery and CSRF. A cross-site request forgery (CSRF) vulnerability occurs when: 1. A web application uses session cookies. 2. The application acts on an HTTP request without verifying that the request was made with the user's consent. If the request does not contain a nonce that proves its provenance, the code that handles the request is vulnerable to a CSRF attack (unless it does not change the state of the application.) This means a web application that uses session cookies has to take special precautions in order to ensure that an attacker can't trick users into submitting bogus requests.[5][1] 3.2.4.2 Impact on Web Application If an administrator for the vulnerable site visits a page containing this code while she has an active session, she will unwittingly create an account for the attacker. It is possible because the application does not have a way to
CHAPTER 3. PROPOSED WORK 30 determine the provenance of the request. Any request could be a legitimate action chosen by the user or a faked action set up by an attacker. The attacker does not get to see the web page that the bogus request generates, so the attack technique is only useful for requests that alter the state of the application. 3.2.4.3 Example: Figure 3.3: Cross-Site Request Forgery Vulnerability. Above figure 3.3 is showing typical example of cross-site request forgery vulnerablity in which hacker want to get authentication to www.facebook.com through hist server posting parameteres to facebooks server. cross-site request forgery can be done by editing XML script as shown below. var req = new XMLHttpRequest(); req.open("POST", "/new_user", true); body = addToPost(body, new_username); body = addToPost(body, new_passwd); req.send(body); An attacker might set up a malicious web site that contains the following code.
CHAPTER 3. PROPOSED WORK 31 var req = new XMLHttpRequest(); req.open("POST", "http://www.example.com/new_user", true); body = addToPost(body, "attacker"); body = addToPost(body, "haha"); req.send(body); Most web browsers send an HTTP header named referrer along with each request. The referrer header is supposed to contain the URL of the referring page, but attackers can forge it, so the referrer header is not useful for determining the provenance of a request. Applications that pass the session identifier on the URL rather than as a cookie do not have CSRF problems because there is no way for the attacker to access the session identifier and include it as part of the bogus request. 3.2.4.4 Recommendations: Applications that use session cookies must include some piece of information in every form post that the back-end code can use to validate the provenance of the request. One way to do that is to include a random request identifier, like this: RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, "/new_user"); body = addToPost(body, new_username); body = addToPost(body, new_passwd); body = addToPost(body, request_id); rb.sendRequest(body, new NewAccountCallback(callback)); Then the back-end logic can validate the request identifier before processing the rest of the form data. When possible, the request identifier should be unique to each server request rather than shared across every request for a particular session. As with session identifiers, the harder it is for an attacker to guess the request identifier, the harder it is to conduct a successful CSRF attack. The token should not be easily guessed and it should be protected in the same way that session tokens are protected. Additional mitigation techniques include:
CHAPTER 3. PROPOSED WORK 32  Framework protection: Most of modern web application frameworks include CSRF protection embedded and they will automatically include and verify CSRF tokens.  Use a Challenge-Response control: Forcing the customer to respond to a challenge sent by the server is a strong defense against CSRF. Some of the challenges that can be used for this purpose are: CAPTCHAs, password re-authentication and one- time tokens.  Check HTTP Referrer/Origin headers: An attacked won't be able to spoof these headers while performing a CSRF attack. This makes these headers a useful method to prevent CSRF attacks.  Double-submit Session Cookie: Sending the session ID Cookie as a hidden form value in addition to the actual session ID Cookie is a good protection against CSRF attacks. The server will check both values and make sure they are identical before processing the rest of the form data. If an attacker submits a form in behalf of a user, he won't be able to modify the session ID cookie value as per the same-origin-policy.  Limit Session Lifetime: When accessing protected resources using a CSRF attack, the attack will only be valid as long as the session ID sent as part of the attack is still valid on the server. Limiting the Session lifetime will reduce the probability of a successful attack.[5][1] 3.2.5 Vulnerability - Full Path Disclosure (FPD) 3.2.5.1 Explanation: Many websites running wordpress are exposing the internal path/full path where the php files are installed when they display a php message error. This is not necessary a wordpress issue it‘s a generic php configuration. WordPress developers don‘t see it as a security risk because considering that potential attackers don‘t have access to the internal structure, even if they know it. Which might not be always true considering. It‘s very simple, it just make a request which generates an error message. If the log is not disabled the internal path is displayed in the error message. For
CHAPTER 3. PROPOSED WORK 33 wordpress there are many known ways to get a message error. A warning or an error message will be displayed in the page which containing the internal path. 3.2.5.2 Impact on Web Application There is no direct impact; however, this information can help an attacker identify other vulnerabilities or help during the exploitation of other identified vulnerabilities. If the webroot is getting leaked, attackers may abuse the knowledge and use it in combination with file inclusion vulnerabilities to steal configuration files regarding the web application or the rest of the operating system.[1] 3.2.5.3 Example If error reporting is enabled then it displays errors which contains full path of current file. <b>Warning</b>: trim() expects parameter 1 to be string, array given in <b>/home/content/15/10734315/html/multishark/wp- includes/query.php</b> on line <b>2625</b><br /> Figure 3.4: Full Path Disclosure vulnerability. 3.2.5.4 Recommendations: How to hide the wordpress internal path? There is a simple solution to configure the server to disable the display of warnings and error logs. Practically there are 3 options to do that:
CHAPTER 3. PROPOSED WORK 34  in the php.ini configuration files  in the .htaccess file, in the root of the wordpress installation  in the php script Disabling Warning and Errors in the php.ini configuration files You have to add any of the following lines: display_errors = 0 display_errors = Off Once you have modified the php.ini file you have to restart the server Disabling Warning and Errors in .htaccess file You have to add any of the following lines: php_flag display_errors off Disabling Warning and Errors in php file You have to add any of the following lines: ini_set('display_errors','Off'); 3.2.6 Vulnerability - Arbitrary code execution 3.2.6.1 Explanation: Developers often directly use or concatenate potentially vulnerable input with file or assume that input files are genuine. When the data is NOT checked properly, this can lead to the vulnerable content being processed or invoked by the web server. Regardless of the language a program is written in, the most devastating attacks often involve remote code execution, whereby an attacker succeeds in executing malicious code in the program's context. If attackers are allowed to upload files to a directory that is accessible from the Web and cause these files to be passed to the PHP interpreter, then they can cause malicious code contained in these files to execute on the server. An attacker can execute arbitrary commands on the system. The web server can be compromised by uploading and executing a web-shell which can run commands, browse system files, browse local resources, attack other servers, and exploit the local vulnerabilities. 3.2.6.2 Example Below are some of the classic examples of :
CHAPTER 3. PROPOSED WORK 35 o Upload .php file into web tree. o Upload .gif to be resized. o Upload huge files. o Upload file containing tags. o Upload .exe file into web tree. The function do_upload() in Upload.php calls move_uploaded_file(). Permitting users to upload files can allow attackers to inject dangerous content or malicious code to run on the server. Example 1: The following code processes uploaded files and moves them into a directory under the Web root. Attackers can upload malicious PHP source files to this program and subsequently request them from the server, which will cause them to be executed by the PHP interpreter. <?php $udir = 'upload/'; // Relative path under Web root $ufile = $udir . basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $ufile)) { echo "Valid upload receivedn"; } else { echo "Invalid upload rejectedn"; } ?> Even if a program stores uploaded files under a directory that isn't accessible from the Web, attackers might still be able to leverage the ability to introduce malicious content into the server environment to mount other attacks. If the program is susceptible to path manipulation, command injection, or remote include vulnerabilities, then an attacker might upload a file with malicious content and cause the program to read or execute it by exploiting another vulnerability.[1]
CHAPTER 3. PROPOSED WORK 36 Figure 3.5: Arbitrary Code Execution Vulnerability. 3.2.6.3 Recommendations: Unless your program specifically requires its users to upload files, disable the file_uploads option in configuration file. File upload option can be disabled by including the following entry in php.ini: file_uploads = 'off' The file_uploads option can also be disabled by including the following entries in the Apache httpd.conf file: php_flag file_uploads off If a program must accept file uploads, then restrict the ability of an attacker to supply malicious content by only accepting the specific types of
CHAPTER 3. PROPOSED WORK 37 content the program expects. Most attacks that rely on uploaded content require that attackers be able to supply content of their choosing and restrictions on this content can greatly limit the range of possible attacks.[1] 3.2.7 Vulnerability - Denial-of-service attack 3.2.7.1 Explanation: Denial of Service (DOS) attack is an attempt by hackers to make a network resource unavailable. It is usually temporary or indefinitely interrupts the host which is connected to the internet. These attacks typically target services hosted on mission critical web servers such as banks, credit card payment gateways.[1] 3.2.7.1.1 Symptoms of DOS Symptoms of Denial of Service attack are given below -  Unusually slow network performance.  Unavailability of a particular web site.  Inability to access any web site.  Dramatic increase in the number of spam emails received.  Long term denial of access to the web or any internet services.  Unavailability of a particular web site. 3.2.7.2 Example Figure 3.6 showing Denial of Service vulnerability in which attacker ping server with huge data which block the network and resource will be unavailable.
CHAPTER 3. PROPOSED WORK 38 Figure 3.6: Denial of Service vulnerability. 3.2.7.3 Impact on Web Application In computer network security, backscatter is a side-effect of a spoofed denial-of-service attack. In this kind of attack, the attacker spoofs (or forges) the source address in IP packets sent to the victim. In general, the victim machine cannot distinguish between the spoofed packets and legitimate packets, so the victim responds to the spoofed packets as it normally would. These response packets are known as backscatter.[1] 3.2.7.4 Recommendations:  Use a QoS feature in the load balancer to send all anonymous sessions to separate application servers in your cluster, while logged-on users use another set. This prevents an application-level anonymous DDOS taking out valuable customers  Using a strong CAPCHA to protect anonymous services  Session timeouts  Have a session-limit or rate-limit on certain types of request like reports. Ensure that you can turn off anonymous access if necessary  Ensure that a user has a limit to the number of concurrent sessions (to prevent a hacked account logging on a million times)  Have different database application users for different services (eg transactional use vs. reporting use) and use database resource management to prevent one type of web request from overwhelming all others  If possible make these constraints dynamic, or at least configurable. This way, while you are under attack, you can set aggressive temporary limits in place ('throttling' the attack), such as only one session per user, and no anonymous access. This is certainly not great for your customers, but a lot better than having no service at all.[1] 3.2.8 Memory Exhaustion Vulnerability
CHAPTER 3. PROPOSED WORK 39 3.2.8.1 Explanation: Memory Exhaustion is one of the most intractable classes of programming errors, for two reasons: 1. The source of the memory corruption and its manifestation may be far apart, making it hard to correlate the cause and the effect. 2. Symptoms appear under unusual conditions, making it hard to consistently reproduce the error. Memory Exhaustion errors can be broadly classified into four categories: 1. Using uninitialized memory: Contents of uninitialized memory are treated as garbage values. Using such values can lead to unpredictable program behavior. 2. Using none-owned memory: It is common to use pointers to access and modify memory. If such a pointer is a null pointer, dangling pointer (pointing to memory that has already been freed), or to a memory location outside of current stack or heap bounds, it is referring to memory that is not then possessed by the program. Using such pointers is a serious programming flaw. Accessing such memory usually causes operating system exceptions, that most commonly lead to a program crash (unless suitable memory protection software is being used). 3. Using memory beyond the memory that was allocated (buffer overflow): If an array is used in a loop, with incorrect terminating condition, memory beyond the array bounds may be accidentally manipulated. Buffer overflow is one of the most common programming flaws exploited by computer viruses, causing serious computer security issues (e.g. return-to-libc attack, stack-smashing protection) in widely used programs. In some cases programs can also incorrectly access the memory before the start of a buffer. 4. Faulty heap memory management: Memory leaks and freeing non-heap or un-allocated memory are the most frequent errors caused by faulty heap memory management.[6] 3.2.8.2 Example
CHAPTER 3. PROPOSED WORK 40 Figure 3.7: Memory Exhaustion vulnerability. 3.2.8.3 Recommendations:  Use a QoS feature in the load balancer.  Strong Garbage Collection Handling.  Reuse of free locations.  Use of safe libraries  Pointer protection  Executable space protection  Deep Testing  Corruption Protection 3.2.9 Vulnerability - File Inclusion 3.2.9.1 Explanation: Situation described below is typical file injection vulnerability and in this situation, without filtering request data, you are vulnerable both for Local File Injection (LFI) and Remote File Injection (RFI).[3] It's also good to remember that: 1. include or require will load and execute any good code in php wheter it is in php file or not. Look here for example of jpg image carring php code (and this file is even rocognized as image/jpg by mimetype!). 2. include or require will also open plain text files, like your etc/hosts without errors if you are working on default Apache/PHP settings. 3. With GET varialbe like yours, in Windows, end user can just use variable with ".." path. So it is possible to check all dirs loosely. 4. Here you can check how you can include remote files. Based on answers there you can easily reconfigure your server/php stack and test vulnerability.
CHAPTER 3. PROPOSED WORK 41 3.2.9.2 Example Figure 3.8: File Inclusion vulnerability. Figure showing an attacker to include and execute a remotely hosted file using a script by including it in the attack page. The attacker can use RFI to run a malicious code either on the client side or on the server.[3] 3.2.9.3 Impact on Web Application File inclusion vulnerability allows an attacker to access unauthorized or sensitive files available on the web server or to execute malicious files on the web server by making use of the ‗include‘ functionality. The impact of this vulnerability can lead to malicious code execution on the server or reveal data present in sensitive files, etc.[3] 3.2.9.4 Recommendations: Information we can conclude that the file inclusion attacks can be at times more harmful than SQL injection, etc — therefore there is a great need to remediate such vulnerabilities. And proper input validation is the only key to avoid such vulnerabilities.[3][5] File Inclusion Vulnerability can be avoided by taken care of following points:  In most cases removal of special characters from variable used to include files is enough to prevent successful exploitation.  Blacklist all the special characters which are not of any use in a filename.  Web Application Firewall can be an efficient solution to prevent vulnerability exploitation  Limit the API to allow inclusion of files only from one allowed directory so that directory traversal can also be avoided.  create a rule that allows only alphabetical characters
CHAPTER 3. PROPOSED WORK 42 3.2.10 Vulnerability - HTML Injection 3.2.10.1 Explanation: HTML injection is an attack that is similar to Cross-site Scripting (XSS). While in the XSS vulnerability the attacker can inject and execute Javascript code, the HTML injection attack only allows the injection of certain HTML tags. When an application does not properly handle user supplied data, an attacker can supply valid HTML code, typically via a parameter value, and inject their own content into the page. This attack is typically used in conjunction with some form of social engineering, as the attack is exploiting a code-based vulnerability and a user's trust.[6][7][8] A possible attack scenario is demonstrated below:  Attacker discovers injection vulnerability and decides to use an HTML injection attack  Attacker crafts malicious link, including his injected HTML content, and sends it to a user via email  The user visits the page due to the page being located within a trusted domain  The attacker's injected HTML is rendered and presented to the user asking for a username and password  The user enters a username and password, which are both sent to the attackers server 3.2.10.2 Example Figure 3.9: HTML Injection vulnerability.
CHAPTER 3. PROPOSED WORK 43 3.2.10.3 Impact on Web Application A malicious attacker can exploit the users of this application if he set up a page that is capturing their cookies and credentials in his server. If he has this page then he can trick the users to enter their credentials by injecting into the vulnerable page a fake HTML login form. Thus the attacker retains control of the script and can update or remove the exploit code at anytime. [6][7] 3.2.10.4 Recommendations:  Your script should filter metacharacters from user input.  mysql_real_escape_string used when insert into database  htmlentities() used when outputting data into webpage  htmlspecialchars / entities encode the special chars, so they're displayed but not interpreted. strip_tags REMOVES them. 3.2.11Other Vulnerabilities 3.2.11.1 Vulnerability- Dangerous Function 3.2.11.1.1 Explanation: The function mysql_escape_string() cannot be used safely. It should not be used. Certain functions behave in dangerous ways regardless of how they are used. Functions in this category were often implemented without taking security concerns into account. $str = mysql_escape_string($str); In this case the dangerous function you are using is mysql_escape_string() The mysql_escape_string() function is unsafe as it does not take into consideration the current character encoding set within the database. It can thus be vulnerable to multi-byte escaping issues. mysql_escape_string() also does not escape the '%' and '_' characters.[7] 3.2.11.1.2 Example HTML markup could be inserted into your DB and used for Cross Site Scripting attacks. Harmful Code:- <?php elseif (function_exists('mysql_escape_string')) { $str = mysql_escape_string($str); }
CHAPTER 3. PROPOSED WORK 44 $item = "Zak's % L o _Laptop"; $escaped_item = mysql_escape_string($item); printf("Escaped string: %sn", $escaped_item); ///Output : Zak's % L o _Laptop ?> 3.2.11.1.3 Recommendations: Functions that cannot be used safely should never be used. If any of these functions occur in new or legacy code, they must be removed and replaced with safe counterparts. mysql_escape_string() function has been deprecated as of PHP 5.3.0. It has been replaced with mysql_real_escape_string(). It is recommended that untrusted data be passed to the function within a single quote delimited value, cast to a numeric type or convert the value to a numeric type. [7] Secure Code:- <?php //Using quote limited values with mysql_real_escape_string $db->query("DELETE FROM table WHERE col1='{mysql_real_escape_string($_GET['ID'])}'); //Casting to a numeric type $db->query("DELETE FROM table WHERE col1=". (int) $_GET['ID'] .");" //Explicitly converting to a numeric type $db->query("DELETE FROM table WHERE col1=". intval($_GET['ID']) .");" ?> 3.2.11.2 Vulnerability- Key Management: Hardcoded Encryption Key Hardcoded encryption keys could compromise system security in a way that cannot be easily remedied. 3.2.11.2.1 Explanation: It is never a good idea to hardcode an encryption key. Not only does hardcoding an encryption key allow all of the project's developers to view the encryption key, it also makes fixing the problem extremely difficult. Once the code is in production, the encryption key cannot be changed without patching the software. If the account protected by the encryption key is compromised, the owners of the system will be forced to choose between security and availability.[8]
CHAPTER 3. PROPOSED WORK 45 3.2.11.2.2 Example The following code uses a hardcoded encryption key to encrypt information: <?php $encryption_key = 'hardcoded_encryption_key'; //$filter=new Zend_Filter_Encrypt('hardcoded_encryption_key'); $filter = new Zend_Filter_Encrypt($encryption_key); $filter->setVector('myIV'); $encrypted = $filter->filter('text_to_be_encrypted'); print $encrypted; ?> This code will run successfully, but anyone who has access to it will have access to the encryption key. Once the program has shipped, there is no going back from the hardcoded encryption key ('hardcoded_encryption_key') unless the program is patched. A devious employee with access to this information can use it to compromise data encrypted by the system.[8] 3.2.11.3 Impact on Web Application Hardcoding an encryption key allow all of the project's developers to view the encryption key, it also makes fixing the problem extremely difficult. Once the code is in production, the encryption key cannot be changed without patching the software. 3.2.11.3.1 Recommendations: Encryption keys should never be hardcoded and should generally be obfuscated and managed in an external source. Storing encryption keys in plaintext anywhere on the system allows anyone with sufficient permissions to read and potentially misuse the encryption key. 3.2.11.4 Vulnerability- Password Management: Hardcoded Password Hardcoded passwords could compromise system security in a way that cannot be easily remedied.[11] 3.2.11.4.1 Explanation: It is never a good idea to hardcode a password. Not only does hardcoding a password allow all of the project's developers to view the password, it also makes
CHAPTER 3. PROPOSED WORK 46 fixing the problem extremely difficult. Once the code is in production, the password cannot be changed without patching the software. If the account protected by the password is compromised, the owners of the system will be forced to choose between security and availability.[9][11] 3.2.11.4.2 Example The following code uses a hardcoded password to connect to a database: <?php $link = mysql_connect($url, 'scott', 'tiger'); if (!$link) { die('Could not connect: ' . mysql_error()); } ?> This code will run successfully, but anyone who has access to it will have access to the password. Once the program has shipped, there is no going back from the database user "scott" with a password of "tiger" unless the program is patched. A devious employee with access to this information can use it to break into the system. 3.2.11.4.3 Impact Hard coding a password allow all of the project's developers to view the password, it also makes fixing the problem extremely difficult. Once the code is in production, the password cannot be changed without patching the software.[11] 3.2.11.4.4 Recommendations: Passwords should never be hardcoded and should generally be obfuscated and managed in an external source. Storing passwords in plaintext anywhere on the system allows anyone with sufficient permissions to read and potentially misuse the password. 3.2.11.5 Vulnerability- Path Manipulation (Input Validation and Representation, Data Flow) Attackers can control the filesystem path argument to file(), which allows them to access or modify otherwise protected files. $tmp = file($dir . 'php_' . $name . '.afm');
CHAPTER 3. PROPOSED WORK 47 $this->fonts[$font] = unserialize($tmp[0]); 3.2.11.5.1 Explanation: Path manipulation errors occur when the following two conditions are met: 1. An attacker can specify a path used in an operation on the filesystem. 2. By specifying the resource, the attacker gains a capability that would not otherwise be permitted. Harmful Code:- <?php $filename = $CONFIG_TXT['sub'] . ".txt"; $handle = fopen($filename,"r"); $amt = fread($handle, filesize($filename)); echo $amt; ?> 3.2.11.5.2 Recommendations: It is always a good programming practice that validates the path or file name before using it. Secure Code:- <?php $filename = $CONFIG_TXT['sub'] . ".txt"; $handle = fopen(getValidFile($filename),"r"); $amt = fread($handle, filesize($filename)); echo $amt; ?> 3.2.11.6 Vulnerability- Hidden Field 3.2.11.6.1 Explanation: Programmers often trust the contents of hidden fields, expecting that users will not be able to view them or manipulate their contents. Attackers will violate these assumptions. They will examine the values written to hidden fields and alter them or replace the contents with attack data.[9][10] 3.2.11.6.2 Example
CHAPTER 3. PROPOSED WORK 48 An <input> tag of type hidden indicates the use of a hidden field. <input type="hidden"> If hidden fields carry sensitive information, this information will be cached the same way the rest of the page is cached. This can lead to sensitive information being tucked away in the browser cache without the user's knowledge.[9][10] 3.2.11.7 Impact on Web Application Browsers add-ons like firebug, inspect element etc allows attacker to get the value of hidden field and manipulate it. Hidden sensitive information can lead to disclouser of crucial information. 3.2.11.8 Recommendations: Expect that attackers will study and decode all uses of hidden fields in the application. Treat hidden fields as untrusted input. Don't store information in hidden fields if the information should not be cached along with the rest of the page.[9][10] 3.2.11.9 Vulnerability - Often Misused: File Upload (Input Validation and Representation, content) Do not allow file uploads if they can be avoided. If a program must accept file uploads, then restrict the ability of an attacker to supply malicious content by only accepting the specific types of content the program expects. Most attacks that rely on uploaded content require that attackers be able to supply content of their choosing. Placing restrictions on the content the program will accept will greatly limit the range of possible attacks. Check file names, extensions, and file content to make sure they are all expected and acceptable for use by the application.[8][11] 3.3 Good Programming practices 3.3.1 Avoid short tags If Short tags are disabled on some server, then all of a sudden the whole php code will be displayed even before you are informed about it. <?= $a = 5;
CHAPTER 3. PROPOSED WORK 49 ?> This will run fine when short codes are enabled, but when not, the whole code will be dumped to the browser.All input coming from the user , in the form of POST and GET must be validated to be acceptable by the application logic.  Check the 'type' of the data  Check range of numbers  Check length of strings  Check emails , urls , dates to be valid  Ensure that data does not contain unallowed characters. 3.3.2 Always name your file as only .php Although this is a not very significant to mention point, but still there have been instances of this particular security flaw. Ensure that all php code files have the extension ".php". Let‘s say the database credentials are stored in a separate configuration file and that the file has been named as 'config.inc'. <?php /*Database connection details*/ $db_host = 'localhost'; $db_user = 'project'; $db_pass = 'secret'; $db_name = 'project_ecommerce'; ?> Now if this file is opened in the browser, the contents will be displayed right away. Hence never name your files to anything else except ‗.php‘. 3.3.3 Salt the passwords and use stronger encryption Md5 is a very popular encryption algorithm/function being used by php developers. The md5 function gives the hash rightaway. <?php $hash = md5($password); ?> However md5 is not a fully secure way to store passwords. Most users tend to keep a 5-8 character password, and whatever be the complexity of such a password, it can be easily cracked by just brute forcing on a normal computer/pc.
CHAPTER 3. PROPOSED WORK 50 Moreover even brute forcing might not be necessary, just typing the hash on google.com would reveal the password on some password cracking/rainbow table website. Although users are repeatedly told to keep a strong password its not enough. To overcome this problem developers often use "salt". The add some more text to the password before hashing it and then do the same when comparing user provided password. <?php $salt = 'SUPER_SALTY'; //Any random non-predictable string $hash = md5($password . $salt); ?> Adding a salt increases the length of the password, and hence its complexity. So the time required for a brute force program to crack it increase by a huge span. Along with salt, its a good practice to use a longer(slower) hash algorithm like sha1, sha2 etc. The slower the hashing algorithm, more the time required by a brute force program and hence better the strength. Bcrypt encryption is even more complex than the sha algorithm and considered more secure. Check the php crypt function.[11] 3.3.4 Regenerate Session ID It is a good idea to regenerate the session id at specific events or intervals. It might help if the earlier session id was hacked. To regenerate the session id use the following function <?php session_regenerate_id(); //changes only session id //or session_regenerate_id(true); ?> The session id should be regenerated atleast when authentication levels change, for example when  a user logs in  a user logs out  a user gets administrative access or change of privilege happens. <?php if(valid_username() and valid_password())
CHAPTER 3. PROPOSED WORK 51 { $_SESSION['logged'] = true; $_SESSION['username'] = $username; } ?> You may even want to regenerate session id every 15 minutes or every 100 requests. <?php session_start(); //increment and check if ( ++$_SESSION['regenerated_count'] > 100 ) { //reset and regenerate $_SESSION['regenerated_count'] = 0; session_regenerate_id(true); } ?> 3.3.5 Store sessions in database By default sessions are stored in files. Many applications are hosted on shared hosting environments where the session files are saved to /tmp directory. Now this directory may be readable to other users. If unencrypted the session information will be plain text in the file : userName|s:5:"ngood";accountNumber|s:9:"123456789"; There are many workarounds for this. Encrypt the session information with suhosin. Store sessions in database. Sessions stored inside database are not visible like files. They are only available to the application using it. 3.3.6 Force single session For a higher level of security, make sure that a user is not logged in from 2 locations at a time. If user try to login from another location, first logout from the previous login. This is useful on websites that exchange confidential data. for example an online banking website. This is easy to implement when sessions are saved in database. Simply delete any previous login record of a username on every login.[7] 3.3.7 Configure the database user with care Make sure the database user does not have privileges to execute command or write to local filesystem. If there is an sql injection vulnerability
CHAPTER 3. PROPOSED WORK 52 somewhere in the website and the database user has write privileges, then this is sufficient for a hacker to take over the server completely just by using simple tool like sql map. So the permissions of the database user should be set according to needs. It is a good idea to have a separate user for use by the web application that has only the minimal required privileges on the database system. Or have separate database users for viewing and modifying the database.[11] 3.3.8 Disable directory content listing Using htaccess Putting the following the .htaccess file shall disable directory listing. Options -Indexes Using index.html If the server does not allow this, then the easiest way is to put a dummy index.html file in all directories. So that when directory path is accessed, the index.html will open up.[9] 3.3.9 Keep resources outside WEB_ROOT When hosting applications on a server, the path is generally like this : /var/www/ OR /home/username/www/ All web content is kept inside www , then only it is accessible on a website. But those contents which are not meant to be directly accessible from a url , can be kept outside the /www. For example uploaded images , or resource files , or files containing database connection parameters or anything. php files to be called by browser in /var/www/ Other resource files in /var/outside/ By doing this the files automatically become invisible to outside world even if directory listing is enabled.[9] 3.3.10 Upload files to a location outside webroot Applications that allow users to upload files can put the uploaded files in a location that is outside the web root. This can help in a situation of arbitrary file upload. If a hacker were to find such a vulnerability he would try to upload a shell script and execute it by triggering from the browser. Now if the file is
CHAPTER 3. PROPOSED WORK 53 outside the web root, then even if the hacker would know the path to the file, it would be harder for him to execute the shell.[10] 3.3.1115. Disable display_errors in your php.ini file Do not wait to turn off display_errors in your php script using ini_set or htaccess or anything similar. Compilation errors that occur before execution of the script starts will not obey any script rules and would be displayed right away. Hence display of errors should be disabled right in the php.ini file in production environment. 3.3.12 Setup correct directory permissions in the production environment Directories should have proper permissions with regard to the need of being writable or not. Keep a separate directory for temp files, cache files and other resource files and mark them writable as needed. Everything else like the directory containing core application code, library files etc should be unwritable. Also directories (like temp) which can contain resource files, or files with other information should be guarded well and be totally inaccessible to the outside web. Use htaccess to block all access to such directories deny from all.[10][11]
CHAPTER 4. PLATFORM OF RESEARCH 54 Chapter 4 Platform of Research Security of web application is an important issue should be taken care by every organization. Security of data and information available is most important. Security Audit of a web application improves the protection by showing the possible threads available by fixing those threads it will be nearly robust. It improves the performance of existing web application. Many testing tools free as well as paid are available. More secure web application attracts more people and provide service guarantee which is the first requirement of a web application these days. The thesis is analyzed from various testing reports testing tools and security audit trails experiments, those were conducted using following tools, add-on and software: Server-Side Script: PHP Client side Script: Javascript Database: Mysql Browser: Mozila Firefox Operating System: Microsoft Windows 7 Professional (64 bit) Add-On: Firebug, Selenium S/w Tools: Burp Suit, Fortify Testing Tool, Acunetix Vulnerability Scanner, DirBuster and other testing tools.
CHAPTER 5. CONCLUSION AND FUTURE WORK 54 Chapter 4 Platform of Research Security of web application is an important issue should be taken care by every organization. Security of data and information available is most important. Security Audit of a web application improves the protection by showing the possible threads available by fixing those threads it will be nearly robust. It improves the performance of existing web application. Many testing tools free as well as paid are available. More secure web application attracts more people and provide service guarantee which is the first requirement of a web application these days. The thesis is analyzed from various testing reports testing tools and security audit trails experiments, those were conducted using following tools, add-on and software: Server-Side Script: PHP Client side Script: Javascript Database: Mysql Browser: Mozila Firefox Operating System: Microsoft Windows 7 Professional (64 bit) Add-On: Firebug, Selenium S/w Tools: Burp Suit, Fortify Testing Tool, Acunetix Vulnerability Scanner, DirBuster and other testing tools.
CHAPTER 5. CONCLUSION AND FUTURE WORK 55 Chapter 5 Conclusion and Future Work 4.1 Conclusion This dissertation presents some basic and advanced methods to understand and prevent web attacks and other vulnerabilities like XSS,SQL Injection, input validation based attacks in a meta programming setting, the domain of web applications. This dissertation describes the first formal, realistic characterization of SQL injection, XSS and other vulnerabilities and presents principled, practical analyses for identifying vulnerabilities and preventing attacks. The analyses can detect and block real attacks and uncover unknown vulnerabilities in real-world code. We studied many existing approaches to detect and prevent these vulnerabilities in an application, giving a brief note on their advantages and disadvantages. All the approaches followed by different methods leads to a very interesting solution; however some failures are associated with almost each one of them at some point. Furthermore these scanners support all web applications, many of them supports only for PHP web applications with known vulnerabilities. We began with a formal definition of Attacks and Vulnerabilities with most common security attacks such as XSS, SQL injection, HTML Injection, etc., those are based on data integrity and sentential forms. Initially, we proposed the first principled definition of XSS injection by explainting the effect and impact with prevention techniques. That untrusted input is permitted to have on SQL queries that a web application constructs. Our characterization employs two primary notions: sentential forms, an abstraction from parsing algorithms used in compilers; and integrity, a fundamental concept in security that forbids untrusted
CHAPTER 5. CONCLUSION AND FUTURE WORK 56 data from modifying trusted data. Our definition provides a solid foundation for prevent attacks. Basics and advance methods to check for attacks and vulnerabilities. 4.2 Future Work - Develop a GUI for the scanner script, so make it easy for anyone to install and use the scanner. - Add full support for all known vulnerabilities for all platform XSS detection techniques which should be platform independent. - Implement a local proxy module to be included in the scanner work, which will make a full vulnerability analysis environment.

Web vulnerabilities

  • 1.
    A Thesis On Preventing Cyber AttackAnd Other Vulnerabilities By Krishna Gehlot
  • 2.
    V ABSTRACT If security ofa web application is weak, the attackers can easily get in. It is relatively easy to compromise a site, but it takes significant resources for a defender to provide even modest security. One of the reasons for this is that current web security technologies are very complex to learn, understand, implement and maintain. As a result, security may be ignored in favour of other concerns. The web needs simpler policy which can stop basic as well as critical cyber attacks in order to level the playing field. With the rise of the Internet, web applications, such as online banking and web- based services, emails, social sites have become integral to many people’s daily lives. Web applications have brought with them new classes of computer security vulnerabilities, such as SQL injection and cross-site scripting (XSS), etc. that in recent years have exceeded previously prominent vulnerability classes, such as buffer overflows, in both reports of new vulnerabilities and reports of exploits. SQL injection and XSS are both instances of the broader class of input validation based vulnerabilities. At their core, both involve one system receiving, transforming, and constructing string values, some of which come from untrusted sources, and presenting those values to another system that interprets them as programs or program fragments. These input validation-based vulnerabilities therefore require fundamentally new techniques to characterize and mitigate them. In this thesis we are providing a vulnerability scanning and analyzing tool of various kinds of SQL injection and Cross Site Scripting (XSS) attacks. Our approach can be used with any web application not only the known ones. As well as it supports the most famous Database management servers, namely MySQL and etc.
  • 3.
    VI List of Abbreviations XSS– Cross Side Scripting. TCP – Transmission Control Protocol. SQL – Structured Query Language. RDBMS – Relational Database Management System SQLi – Structured Query Language Improved FPD – Full Path Disclosure. CLI – Command Line Interface. HTML – Hyper Text Markup Language. CSRF – Cross-Site Request Forgery. OWASP – Open Web Application Security Project. DOS – Denial of Service
  • 4.
    VII Contents Declaration II Certificate III AcknowledgmentsIV Abstract V List of Abbreviations VI Contents VII List of Figures IX List of Tables X 1 Introduction 1 1.1 Web Application Security . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 What is Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3.1 Active Attack. . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.3.2 Passive Attack. . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.4 What is Vulnerability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 2 Literature Survey 8 2.1 Web Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Web Application Vulnerability . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Most Common Security Issue . . . . . . . . . . . . . . . . . . . . . . 14 3 Proposed Work 17 3.1 Technologies Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.2 Description of proposed work . . . . . . . . . . . . . . . . . . . . . . 18 3.3 Good Programming Practice . . . . . . . . . . . . . . . . . . . . . . 48
  • 5.
    VIII 4 Platform ofResearch 54 5 Conclusion and Future Work 55 Conclusion ....................................................................................................55 Future Work..........................................................................................................56 REFERENCES 57
  • 6.
    IX List of Figures S.NoFigure Description Page No 1 Figure 1.1: Distributed Denial of Service(SDoS) Attack 5 2 Figure 1.2: Spoofing Attack 5 3 Figure 1.3: Man-in-the-middle attack 6 4 Figure 1.4: Ping of Death Attack. 6 5 Figure 1.5: Pinging an IP with ping of death. 7 6 Figure 1.6: Ping Flood Attack. 7 7 Figure 1.7: Port Scanner Attack. 8 8 Figure 1.8: Idle Scan Attack. 9 9 Figure 1.9: Exploit vulnerability process diagram. 10 10 Figure 2.1: Web application system architecture 12 11 Figure 2.2: Top vulnerabilities in March 2012 13 12 Figure 3.1: Cross Side Scripting Vulnerability 22 13 Figure 3.2: SQL Injection Vulnerability. 26 14 Figure 3.3: Cross-Site Request Forgery Vulnerability. 30 15 Figure 3.4: Full Path Disclosure vulnerability. 33 16 Figure 3.5: Arbitrary Code Execution Vulnerability. 36 17 Figure 3.6: Denial of Service vulnerability. 38 18 Figure 3.7: Memory Exhaustion vulnerability. 40 19 Figure 3.8: File Inclusion vulnerability. 41
  • 7.
    X List of Tables Relationshipbetween New Top Ten, Last year’s top ten and WAS top vulnerabilities [1]..............................................................................................................13
  • 8.
    CHAPTER 1. INTRODUCTION 1 Chapter1 Introduction The increased use of internet and web applications has become an important part of our society. Web applications, web services and websites plays important role for any business. Web applications are being used almost everywhere like homes, colleges, schools, organizations, institutes, businesses etc. Generally, programmers and developers do not care about many additional configurations and connect applications to the Internet immediately. Most programmers are not technically sound to do advance programming. Due to this negligence to security of code, it motivates attackers to hack less secure web application. To improve the security of the web applications and web services this material is presented, this document is obtained from the Analysis done on Code, Audit, Network reports, Security reports of various PHP Web Applications, and other sources of NIC’s best practices. This Web Security Standards and Practices document establishes a baseline of security related requirements for all web services and websites, including branded applications supported or hosted by 3rd parties. Advances in web technologies coupled with a changing business environment, mean that web applications are becoming more prevalent in corporate, public and Government services today. Although web applications can provide convenience and efficiency, there are also a number of new security threats, which could potentially pose significant risks to an organisation‟s information technology infrastructure if not handled properly.[1][2] Web Application Firewalls (WAF). If all the security measures deployed ahead of the WAF were truly effective in protecting the application, there would be no need for a Web Application Attack Report[3]. But even with all those layers protecting the endpoint, the network, and everything in between user and application, threats still manage to sneak through to the application, proving once again that Improved Secure Sphere WAF is the last line of defense for web applications. So, until all security products are perfect, and applications can protect against all attacks, there will be a WAAR.[4]
  • 9.
    CHAPTER 1. INTRODUCTION 2 ApplicationDefense Center is a proud contributor of valuable cyber crime trends and shares information with the security community of customers, vendors and partners to defend better against existing and new threats. The purpose of this document is to provide coding standards, which are based on the practices, to minimize security and vulnerability exploits due to improper and non standard coding practices. It also provides references to information about common web security vulnerabilities to enhance understanding of the root causes of such issues and how to remediate, prevent or eliminate them appropriately. This document is created to focus corporations and government agencies on the most serious of these vulnerabilities. Web application security has become a hot topic as companies race to make content and services accessible though the web. At the same time, hackers are turning their attention to the common weaknesses created by application developers.[2] 1.1 Web Application Security Web application security is a branch of Information Security that deals specifically with security of websites, web applications and web services. At a high level, Web application security draws on the principles of application security but applies them specifically to Internet and Web systems. With the emergence of Web 2.0, increased information sharing through social networking and increasing business adoption of the Web as a means of doing business and delivering service, websites are often attacked directly. Hackers either seek to compromise the corporate network or the end-users accessing the website by subjecting them to drive-by downloading. As a result, industry is paying increased attention to the security of the web applications themselves in addition to the security of the underlying computer network and operating systems.[4] 1.2Overview Web applications serve a wide range of purposes, from social networking, sensitive data management to online shopping. The advent of smart mobile devices enables users to access web applications even on the go. A recent Symantec Internet security threat report states that the number of reported web vulnerabilities increased from 4,989 in 2011 to 5,291 in 2012, incurring an average cost of $591,780 for businesses [68]. Furthermore, web vulnerabilities are widespread. A WhiteHat security statistics report published in 2013 shows that 86% of all the surveyed websites had at least one serious vulnerability
  • 10.
    CHAPTER 1. INTRODUCTION 3 during2012, and the number of serious vulnerabilities per website was 56 on average. Recent years have witnessed the rapid growth of web applications and their code complexity. Web applications have evolved from sets of simple, static web pages, to feature-rich Web 2.0 applications which frequently integrate third-party services. Unfortunately, the more features that a modern web application possesses, the larger attack surface it often exposes to attackers. With the incorporation of client-side JavaScript code, attackers can inject malicious JavaScript code in user inputs and exploit various ways that web browsers invoke their JavaScript engines. In cases where web applications behave differently to administrators and normal users, attackers can break authentication processes and access sensitive information and functionality. In recent years, the integration of third-party services has become popular, giving attackers a new opportunity to exploit miscommunications between servers and service providers. The best practice for web security is to build an application with security in mind end-to-end. However, many web developers are unfamiliar with various attack vectors, especially application-specific ones. Application- specific vulnerabilities in web applications are especially challenging to detect. When building an application, developers often have a clear picture of what the ideal application should be in their minds. Unfortunately, in practice, the implemented application often does more than what is intended. Put it another way, unexpected user inputs and logic flows can allow attackers to abuse implemented but insufficiently guarded application-specific functionality in dangerous ways. The uniqueness and complexity of logic flows complicate the establishment of a general line of defense against application-specific attacks. This dissertation focuses on detecting crucial, ungrounded assumptions that web developers make about user inputs and logic flows in web applications. While existing solutions mainly focus on vulnerabilities related to untrusted user inputs, the key observation of this dissertation is that it is also important to validate critical assumptions on logic flows which are application-specific. Less traveled paths in web applications may indeed lead to fruitful attacks. Inferring and enforcing such implicit assumptions on logic flows are vital yet challenging for web application security[5]. 1.3What is Attack In computer and computer networks an attack is any attempt to destroy, expose, alter, disable, steal or gain unauthorized access to or make unauthorized use of an asset. an assault on system security that derives from an intelligent threat, i.e., an intelligent act that is a deliberate attempt (especially in the sense of a method or technique) to evade security services and violate the security policy of a system. An attack, via cyberspace, targeting an enterprise’s use of
  • 11.
    CHAPTER 1. INTRODUCTION 4 cyberspacefor the purpose of disrupting, disabling, destroying, or maliciously controlling a computing environment/infrastructure; or destroying the integrity of the data or stealing controlled information.[1] An attack can be can be further classified into two parts: 1. Active 2. Passive. 1.3.1 Active Attack An "active attack" attempts to alter system resources or affect their operation. The following is a partial short list of active attacks: 1. Denial-of-service attack 2. Spoofing 3. Man in the middle 4. Ping flood 5. Ping of death 1.3.1.1 Denial-of-Service Attack Denial-of-Service attack (DoS attack) is a cyber-attack where the perpetrator seeks to make a machine or network resource unavailable to its intended users by temporarily or indefinitely disrupting services of a host connected to the Internet. Denial of service is typically accomplished by flooding the targeted machine or resource with superfluous requests in an attempt to overload systems and prevent some or all legitimate requests from being fulfilled.[1]
  • 12.
    CHAPTER 1. INTRODUCTION 5 Figure1.1: Distributed Denial of Service(SDoS) Attack.[1] 1.3.1.2 Spoofing Attack Spoofing attack is a situation in which one person or program successfully masquerades as another by falsifying data, thereby gaining an illegitimate advantage.[1] Figure 1.2: Spoofing Attack.[1]
  • 13.
    CHAPTER 1. INTRODUCTION 6 1.3.1.3Man-in-the-middle Attack Man-in-the-middle attack (MITM, sometimes called a "bucket brigade attack") is an attack where the attacker secretly relays and possibly alters the communication between two parties who believe they are directly communicating with each other.[1][2] Figure 1.3: Man-in-the-middle attack. 1.3.1.4 Ping of Death Attack A ping of death is a type of attack on a computer system that involves sending a malformed or otherwise malicious ping to a computer.[1] Figure 1.4: Ping of Death Attack.[1]
  • 14.
    CHAPTER 1. INTRODUCTION 7 Figure1.5: Pinging an IP with ping of death.[1] 1.3.1.5 Ping flood Attack A ping flood is a simple denial-of-service attack where the attacker overwhelms the victim with the flood option of ping which sends ICMP packets as fast as possible without waiting for replies.[1] Figure 1.6:Ping Flood Attack.[1] 1.3.2 Passive Attack
  • 15.
    CHAPTER 1. INTRODUCTION 8 A"passive attack" attempts to learn or make use of information from the system but does not affect system resources.[1] The following is a partial short list of passive attacks: 1. Wiretapping 2. Port scan 3. Idle scan 1.3.2.1 Telephone tapping (Wiretapping) Telephone tapping is the monitoring of telephone and Internet conversations by a third party, often by covert means. The wire tap received its name because, historically, the monitoring connection was an actual electrical tap on the telephone line. Legal wiretapping by a government agency is also called lawful interception. Passive wiretapping monitors or records the traffic.[1] 1.3.2.2 Port Scanner Port scanner is an application designed to probe a server or host for open ports. This is often used by administrators to verify security policies of their networks and by attackers to identify network services running on a host and exploit vulnerabilities. Figure 1.7: Port Scanner Attack. 1.3.2.3 Idle Scan The idle scan is a TCP port scan method that consists of sending spoofed packets to a computer to find out what services are available. This is accomplished by impersonating another computer called a "zombie" (that is not transmitting or receiving information) and observing the behavior of the
  • 16.
    CHAPTER 1. INTRODUCTION 9 ''zombie''system. Figure 1.8: Idle Scan Attack. 1.4What is Vulnerability In computer security, a vulnerability is a weakness which allows an attacker to reduce a system's information assurance. Vulnerability is the intersection of three elements: a system susceptibility or flaw, attacker access to the flaw, and attacker capability to exploit the flaw.[1] To exploit a vulnerability, an attacker must have at least one applicable tool or technique that can connect to a system weakness. In this frame, vulnerability is also known as the attack surface. Figure 1.9 is showing vulnerability process diagram.
  • 17.
    CHAPTER 1. INTRODUCTION 10 Figure1.9: Exploit vulnerability process diagram. A threat agent through an attack vector exploits a weakness (vulnerability) of the system and the related security controls, causing a technical impact on an IT resource (asset) connected to a business impact.[2]
  • 18.
    CHAPTER 2. LITERATURESURVEY 11 Chapter 2 Literature Survey This thesis aims to advance the security against web security attacks by using some prevention techniques each of which is capable to hijack the entire system or web application. So for the guarantee of security of a web application we choose to build exploit prevention techniques for their low security performance overhead and the ease of adoption, i.e., more practical. But comparing to existing prevention techniques, our solutions are based on basic security principles so they are able to completely block one type of exploit technique and withstand the rapidly evolving arm race from offensive technologies. 2.1 Web Applications Web applications enable much of today’s online business including banking, shopping, university admissions, email, social networking, and various governmental activities. They have become ubiquitous because users only need a web browser and an Internet connection to receive a system-independent interface to some dynamically generated content. The data web that applications handle, such as credit card numbers and product inventory data, typically has significant value both to the users and to the service providers. Additionally, users care that web pages behave as trusted servers intend because web browsers run on users’ local systems and often have bugs that could be exploited by maliciously written pages.[3]
  • 19.
    CHAPTER 2. LITERATURESURVEY 12 Figure 2.1: Web application system architecture. Figure 1.1 shows typical system architecture for web applications. This three-tiered architecture consists of a web browser, which functions as the user interface; a web application server, which manages the business logic; and a database server, which manages the persistent data 2.2 Web Application Vulnerabilities so far The majority of web application attacks occur through cross-site scripting (XSS) and SQL injection attacks which typically result from flawed coding, and failure to sanitize input to and output from the web application. These are ranked in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors. Phishing is another common threat to the Web application and global losses from this type of attack in 2012 were estimated at $1.5 billion. According to the security vendor Cenzic, the top vulnerabilities in March 2016 include following vulnerabilities showing in figure:
  • 20.
    CHAPTER 2. LITERATURESURVEY 13 Figure 2.2: top vulnerabilities in March 2012. [1] The table below highlights the relationship between the new Top Ten, last year’s Top Ten, and the WAS TC Thesaurus. New Top Ten 2007 Top Ten 2006 New WAS Thesaurus A1 Unvalidated Input A1 Unvalidated Parameters Input Validation A2 Broken Access Control A2 Broken Access Control Access Control A3 Broken Authentication and Session Management A3 Broken Account and Session Management Authentication and Session Management A4 Cross Site Scripting (XSS) Flaws A4 Cross Site Scripting (XSS) Flaws Input Validation->Cross site scripting A5 Buffer Overflows A5 Buffer Overflows Buffer Overflows A6 Injection Flaws A6 Command Injection Flaws Input Validation- >Injection A7 Improper Error Handling A7 Error Handling Problems Error Handling A8 Insecure Storage A8 Insecure Use of Data Protection
  • 21.
    CHAPTER 2. LITERATURESURVEY 14 Cryptography A9 Denial of Service N/A Availability A10 Insecure Configuration Management A10 Web and Application Server Misconfiguration Application Configuration Management Infrastructure Configuration Management 2.3 Most Common Security Issues and Vulnerabilities The following is a short summary of the most significant web application security vulnerabilities. Each of these is described in more detail in the following next chapter. 2.3.1 Broken Authentication and Session Management The potential threat here is that attackers might compromise passwords, keys, or authentication tokens in order to assume the identity of other users. Authentication functions in a web application are not deployed precisely that gives hacker privilege to steal information like session tokens, passwords, keys etc. This flaw is caused when account credentials and session tokens are not properly protected.[1][5] 2.3.2 SQL Injection (SQLi) SQL Injection (SQLi) refers to an injection attack wherein an attacker can execute malicious SQL statements (also commonly referred to as a malicious payload) that control a web application’s database server (also commonly referred to as a Relational Database Management System – RDBMS). Since an SQL Injection vulnerability could possibly affect any website or web application that makes use of an SQL-based database, the vulnerability is one of the oldest, most prevalent and most dangerous of web application vulnerabilities.[5] 2.3.3 Cross-site Scripting In this security issue web application takes unreliable data and revert it back to the web browser. The potential threat of XSS is allowing the execution of scripts in the victim's browser that could hijack user sessions, deface websites, and possibly introduce worms, redirect to malicious URL,
  • 22.
    CHAPTER 2. LITERATURESURVEY 15 deface websites etc. This flaw is caused by the improper validation of user- supplied data when an application takes that data and sends it to a web browser without first validating or encrypting the content.[5] 2.3.4 Cross-site request forgery Hackers can create malicious web pages which produce fake requests that are almost like real ones and forces and user to perform un- desirable acts on a web application in which they are currently logged in. If CSRF attack is successful, it can force the end user to execute state changing requests like changing their email address, transferring funds etc. If the victim is an administrative account, CSRF can compromise the entire web application. CSRF takes benefit of the fact that most web applications permit hackers to guess all the information of a particular individual.[5] 2.3.5 Full Path Disclosure (FPD) Full Path Disclosure (FPD) is the revelation of the full operating path of a vulnerable script. The FPD bug is executed by injecting unexpected characters into certain parameters of a web-page. The script doesn't expect the injected character and returns an error message that includes information of the error, as well as the operating path of the targeted script. The attackers can use this weakness to steal sensitive data, or conduct more serious attacks. Applications can unintentionally leak information.[5] 2.3.6 Arbitrary Code Execution Arbitrary code execution is a program that is designed to exploit such vulnerability that it allows web application to execute Arbitrary code is called an arbitrary code execution exploit. Most of these vulnerabilities allow the execution of machine code and most exploits therefore inject and execute shell code to give an attacker an easy way to manually run arbitrary commands.[1] 2.3.7 Denial-of-service attack Denial-of-service attack In computing, a denial-of-service attack (DoS attack) is a cyber-attack where the perpetrator seeks to make a machine or network resource unavailable to its intended users by temporarily or indefinitely disrupting services of a host connected to the Internet.[1] 2.3.8 Memory corruption Memory corruption occurs in a computer program when the
  • 23.
    CHAPTER 2. LITERATURESURVEY 16 contents of a memory location are unintentionally modified due to programming errors; this is termed violating memory safety. When the corrupted memory contents are used later in that program, it leads either to program crash or to strange and bizarre program behavior. Nearly 10% of application crashes on Windows systems are due to heap corruption.[1] 2.3.9 HTML Injection HTML Injection: It is a sort of injection attack that happens when an end user has the power to control an input point and is capable of injecting random HTML code into an unprotected web page. This type attack is used to steal user’s cookie, modify web page for malicious purpose etc.[1]
  • 24.
    CHAPTER 3. PROPOSEDWORK 17 Chapter 3 Proposed Work The challenge of identifying the web application vulnerabilities is a virtually impossible task. There is not even widespread agreement on exactly what is included in the term ―web application security.‖ Some have argued that we should focus only on security issues that affect developers writing custom web application code. Others have argued for a more expansive definition that covers the entire application layer, including libraries, server configuration, and application layer protocols. In the hopes of addressing the most serious risks facing organizations, This document give a relatively broad interpretation to web application security, while still keeping clear of network and infrastructure security issues. Another challenge to this effort is that each specific vulnerability is unique to a particular organization‘s website. There would be little point in calling out specific vulnerabilities in the web applications of individual organizations, especially since they are hopefully fixed soon after a large audience knows of their existence. Therefore, in this thesis we have chosen to focus on the top classes, types, or categories of web application vulnerabilities. 3.1Technologies Used To fix various vulnerabilities we are working on following technologies and support : 1. PHP 2. Mysqli 3.1.1 PHP
  • 25.
    CHAPTER 3. PROPOSEDWORK 18 PHP is a server-side scripting language designed primarily for web development but also used as a general-purpose programming language. PHP code may be embedded into HTML or HTML5 markup, or it can be used in combination with various web template systems, web content management systems and web frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the web server or as a Common Gateway Interface (CGI) executable. The web server software combines the results of the interpreted and executed PHP code, which may be any type of data, including images, with the generated web page. PHP code may also be executed with a command-line interface (CLI) and can be used to implement standalone graphical applications. 3.1.2Mysqli The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP programming language to provide an interface with MySQL databases. There are three main API options when considering connecting to a MySQL database server: PHP's MySQL Extension. PHP's MySQLi Extension. PHP Data Objects (PDO) The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which, (according to the PHP website) are:  An object oriented interface  Support for prepared statements  Support for multiple statements  Support for transactions  Enhanced debugging support  Embedded server support  More powerful Functionality 3.2 Description of Proposed work Various vulnerabilities along with their definition, impact, example and protection methods will be discussed with their Symptom as below. 3.2.1 Vulnerability - Broken authentication and session management:
  • 26.
    CHAPTER 3. PROPOSEDWORK 19 3.2.1.1 Explanation Broken authentication and session management is related to access control, sometimes called authorization, is how a web application grants access to content and functions to some users and not others. These checks are performed after authentication, and govern what ‗authorized‘ users are allowed to do. Access control sounds like a simple problem but is insidiously difficult to implement correctly. A web application‘s access control model is closely tied to the content and functions that the site provides. In addition, the users may fall into a number of groups or roles with different abilities or privileges.[5] 3.2.1.2 Impact on Web Application All known web servers, application servers, and web application environments are susceptible this issues. Even if a site is completely static, if authentication is not implemented properly, hackers could gain access to sensitive files and deface the site, or perform other mischief. 3.2.1.3 Detection of vulnerability Both code review and penetration testing can be used to diagnose broken authentication and session management problems. 3.2.1.4 Recommendation Defining and documenting your site‘s policy with respect to securely managing users credentials is a good first step. Ensuring that your implementation consistently enforces this policy is key to having a secure and robust authentication and session management mechanism. Some critical areas include:  Password Strength - passwords should have restrictions that require a minimum size and complexity for the password. Complexity typically requires the use of minimum combinations of alphabetic, numeric, and/or non-alphanumeric characters in a user‘s password (e.g., at least one of each). Users should be required to change their password periodically. Users should be prevented from reusing previous passwords.  Password Use - Users should be restricted to a defined number of login attempts per unit of time and repeated failed login attempts should be logged. Passwords provided during failed login attempts should not be recorded, as this may expose a user‘s password to whoever can gain access to this log. The system should not indicate whether it was the
  • 27.
    CHAPTER 3. PROPOSEDWORK 20 username or password that was wrong if a login attempt fails. Users should be informed of the date/time of their last successful login and the number of failed access attempts to their account since that time.  Password Change Controls - A single password change mechanism should be used wherever users are allowed to change a password, regardless of the situation. Users should always be required to provide both their old and new password when changing their password (like all account information). If forgotten passwords are emailed to users, the system should require the user to re-authenticate whenever the user is changing their e-mail address, otherwise an attacker who temporarily has access to their session (e.g., by walking up to their computer while they are logged in) can simply change their e-mail address and request a ‗forgotten‘ password be mailed to them.  Password Storage - All passwords must be stored in either hashed or encrypted form to protect them from exposure, regardless of where they are stored. Hashed form is preferred since it is not reversible. Encryption should be used when the plaintext password is needed, such as when using the password to login to another system. Passwords should never be hardcoded in any source code. Decryption keys must be strongly protected to ensure that they cannot be grabbed and used to decrypt the password file.  Protecting Credentials in Transit - The only effective technique is to encrypt the entire login transaction using something like SSL. Simple transformations of the password such as hashing it on the client prior to transmission provide little protection as the hashed version can simply be intercepted and retransmitted even though the actual plaintext password might not be known.  Session ID Protection – Ideally, a user‘s entire session should be protected via SSL. If this is done, then the session ID (e.g., session cookie) cannot be grabbed off the network, which is the biggest risk of exposure for a session ID. If SSL is not viable for performance or other reasons then session IDs themselves must be protected in other ways. First, they should never be included in the URL as they can be cached by the browser, sent in the referrer header, or accidentally forwarded to a ‗friend‘. Session IDs should be long, complicated, random numbers that cannot be easily guessed. Session IDs can also be changed frequently
  • 28.
    CHAPTER 3. PROPOSEDWORK 21 during a session to reduce how long a session ID is valid. Session IDs must be changed when switching to SSL, authenticating, or other major transitions. Session IDs chosen by a user should never be accepted.  Account Lists - Systems should be designed to avoid allowing users to gain access to a list of the account names on the site. If lists of users must be presented, it is recommended that some form of pseudonym (screen name) that maps to the actual account be listed instead. That way, the pseudonym can‘t be used during a login attempt or some other hack that goes after a user‘s account.  Browser Caching – Authentication and session data should never be submitted as part of a GET, POST should always be used instead. Authentication pages should be marked with all varieties of the no cache tag to prevent someone from using the back button in a user‘s browser to backup to the login page and resubmit the previously typed in credentials. Many browsers now support the AUTOCOMPLETE=OFF flag to prevent storing of credentials in autocomplete caches.  Trust Relationships – Your site architecture should avoid implicit trust between components whenever possible. Each component should authenticate itself to any other component it is interacting with unless there is a strong reason not to (such as performance or lack of a usable mechanism). If trust relationships are required, strong procedural and architecture mechanisms should be in place to ensure that such trust cannot be abused as the site architecture evolves over time.[6] 3.2.2 Vulnerability - Cross-site scripting : 3.2.2.1 Explanation Cross-site scripting (XSS) vulnerabilities occur when an attacker uses a web application to send malicious code, generally in the form of a script, to a different end user. These flaws are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating it. An attacker can use cross site scripting to send 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
  • 29.
    CHAPTER 3. PROPOSEDWORK 22 tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page.[5] XSS attacks can generally be categorized into two categories:  Stored: Stored attacks are those where the injected code 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.  Reflected: Reflected attacks are those where the injected code is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web server. When a user is tricked into clicking on a malicious link or submitting a specially crafted form, the injected code travels to the vulnerable web server, which reflects the attack back to the user‘s browser. The browser then executes the code because it came from a ‗trusted‘ server. 3.2.2.2 Impact on Web Application All known web servers, application servers, and web application environments are susceptible to at XSS. Even if a site is completely static, if it is not protected properly, hackers could gain access to sensitive files and deface the site, or perform other mischief.[5] 3.2.2.3 Example
  • 30.
    CHAPTER 3. PROPOSEDWORK 23 Figure 3.1: Cross Side Scripting Vulnerability Above Figure showing that malicious code is entered into the text box, which allow program to return all company name as result to the attacker. 3.2.2.4 Detection of vulnerability XSS flaws can be difficult to identify and remove from a web application. The best way to find flaws is to perform a security review of the code and search for all places where input from an HTTP request could possibly make its way into the HTML output. Note that a variety of different HTML tags can be used to transmit a malicious JavaScript. Nessus, Nikto, and some other available tools can help scan a website for these flaws, but can only scratch the surface. If one part of a website is vulnerable, there is a high likelihood that there are other problems as well.[6] 3.2.2.5 Recommendations: Since XSS vulnerabilities occur when an application includes malicious data in its output, one logical approach is to validate data immediately before it leaves the application. However, because web applications often have complex and intricate code for generating dynamic content, this method is prone to errors of omission (missing validation). An effective way to mitigate this risk is to also perform input validation for XSS. Web applications must validate their input to prevent other vulnerabilities, such as SQL injection, so augmenting an application's existing input validation mechanism to include checks for XSS is generally relatively easy.[1] The most secure approach to validation for XSS is to create a whitelist of safe characters that are allowed to appear in HTTP content and accept input composed exclusively of characters in the approved set. For example, a valid username might only include alpha-numeric characters or a phone number might only include digits 0-9 A more flexible, but less secure approach is known as blacklisting. In which selectively rejects or escapes potentially dangerous characters before using the input. In order to form such a list, you first need to understand the set of characters that hold special meaning for web browsers.[6]
  • 31.
    CHAPTER 3. PROPOSEDWORK 24 In the content of a block-level element (in the middle of a paragraph of text):  "<" is special because it introduces a tag.  "&" is special because it introduces a character entity.  ">" is special because some browsers treat it as special, on the assumption that the author of the page intended to include an opening "<", but omitted it in error.  In attribute values enclosed with double quotes, the double quotes are special because they mark the end of the attribute value.  In attribute values enclosed with single quote, the single quotes are special because they mark the end of the attribute value.  In attribute values without any quotes, white-space characters, such as space and tab, are special.  "&" is special when used with certain attributes, because it introduces a character entity.  Non-ASCII characters (that is, everything above 128 in the ISO-8859- 1 encoding) are not allowed in URLs, so they are considered to be special in this context.  The "%" symbol must be filtered from input anywhere parameters encoded with HTTP escape sequences are decoded by server-side code. For example, "%" must be filtered if input such as "%68%65%6C%6C%6F" becomes "hello" when it appears on the web page in question.  Within the body of a <SCRIPT> </SCRIPT>:  The semicolon, parenthesis, curly braces, and new line should be filtered in situations where text could be inserted directly into a pre- existing script tag. [5] Example: <?php $string = "A 'heading' is <u>underlined</u>"; // Outputs: A 'heading' is &lt;u&gt;underlined&lt;/u&gt; echo htmlentities($string); // Outputs: A &#039;heading&#039; is &lt;u&gt;underlined&lt;/u&gt;gt; echo htmlentities($str, ENT_QUOTES); ?>
  • 32.
    CHAPTER 3. PROPOSEDWORK 25 3.2.3 Vulnerability - SQL Injection: 3.2.3.1 Explanation: Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. Attackers trick the interpreter into executing unintended commands via supplying specially crafted data. Injection flaws allow attackers to create, read, update, or delete any arbitrary data available to the application. In the worst case scenario, these flaws allow an attacker to completely compromise the application and the underlying systems, even bypassing deeply nested firewalled environments.SQL Injection (SQLi) is an attack that exploits a security vulnerability occurring in the database layer of an application (such as queries). Using SQL injection, the attacker can extract or manipulate the web application‘s data. The attack is viable when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed, and there by unexpectedly executed.[5] SQL injection errors occur when: 1. Data enters a program from an untrusted source. 2. The data is used to dynamically construct a SQL query. 3.2.3.2 Impact on Web Application Only pure static then only it is safe from SQL Injection flaws. Other than that all web application frameworks that use sql, mysql and other sql product as database or invoke sql database and fuctions are vulnerable to SQL injection attacks. This includes any components of the framework that might use back- end interpreters. SQL Injection can be caused to disclose some critical information stored in Database. Sharing the critical information can be cause to disaster. 3.2.3.3 Example Example 1: The following code dynamically constructs and executes a SQL query that searches for login detail matching a specified username. The query restricts the login detail displayed to those where the loginuser matches the user name of the currently-authenticated user. <?php $userName = $_SESSION['userName']; $password = $_POST['password']; $query = "SELECT * FROM login WHERE password = '$password ' AND
  • 33.
    CHAPTER 3. PROPOSEDWORK 26 loginuser = '$userName' "; $result = mysql_query($query); The query that this code intends to execute follows: SELECT * FROM login WHERE password = < password > AND loginuser = <userName> ; ?> Figure 3.2: SQL Injection Vulnerability. However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name 9929913899 enters the string "9929913899' OR 1=1" for User Name and password for password, then the query becomes the following: SELECT * FROM login WHERE password = 'password' AND loginuser = '9929913899' or 1=1 ; The addition of the OR '1=1' condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query: SELECT * FROM login; This simplification of the query allows the attacker to bypass the requirement that the query only return items owned by the authenticated user; the query now returns all entries stored in the login table, regardless of their specified owner, which contain username and password of all login that should
  • 34.
    CHAPTER 3. PROPOSEDWORK 27 not happen. 3.2.3.4 Detection of vulnerability However, there are many ways around to find out if our web application is infected through SQL Injection vulnerability. Online tools can identify if system is vulnerable. Deep Penetration testing can be used to identify and diagnose SQL Injection vulnerability. Stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks. 3.2.3.5 Recommendations: When a SQL query is constructed, the programmer knows what should be interpreted as part of the command and what should be interpreted as data. Parameterized SQL statements can enforce this behavior by disallowing data- directed context changes and preventing nearly all SQL injection attacks. Protection from SQL Injection can be done by using two techniques  Input validation. Use a standard input validation mechanism to validate all input data for length, type, syntax, and business rules before accepting the data to be displayed or stored. Use an "accept known good" validation strategy. Reject invalid input rather than attempting to sanitize potentially hostile data. Do not forget that error messages might also include invalid data.  Use strongly typed parameterized query APIs with placeholder substitution markers, even when calling stored procedures  Enforce least privilege when connecting to databases and other backend systems  Avoid detailed error messages that are useful to an attacker  Use stored procedures since they are generally safe from SQL Injection. However, be careful as they can be injectable (such as via the use of exec() or concatenating arguments within the stored procedure)  Do not use dynamic query interfaces (such as mysql_query() or similar)
  • 35.
    CHAPTER 3. PROPOSEDWORK 28  Do not use simple escaping functions, such as PHP‘s addslashes() or character replacement functions like str_replace("‘", "‘‘"). These are weak and have been successfully exploited by attackers. For PHP, use mysql_real_escape_string() if using MySQL, or preferably use PDO which does not require escaping.When using simple escape mechanisms, note that simple escaping functions  Cannot escape table names! Table names must be legal SQL, and thus are completely unsuitable for user supplied input.  Watch out for canonicalization errors. Inputs must be decoded and canonicalized to the application‘s current internal representation before being validated. Make sure that your application does not decode the same input twice. Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they have been checked When connecting to MySQL, the previous example can be rewritten to use parameterized SQL statements (instead of concatenating user supplied strings) as follows: <?php $mysqli = new mysqli($host,$dbuser, $dbpass, $db); $userName = $_SESSION['userName']; $itemName = $_POST['itemName']; $query = "SELECT * FROM login WHERE loginuser = ? AND password = ?"; $stmt = $mysqli->prepare($query); $stmt->bind_param('ss',$username,$password); $stmt->execute(); ?> The MySQL Improved extension (mysqli) is available for PHP5 users of MySQL. Code that relies on a different database should check for similar extensions. 3.2.4 Vulnerability - Cross-Site Request Forgery 3.2.4.1 Explanation: Cross site request forgery is not a new attack, but is simple and devastating. A CSRF attack forces a logged-on victim‘s browser to send a request to a vulnerable web application, which then performs the chosen action on behalf of the victim.
  • 36.
    CHAPTER 3. PROPOSEDWORK 29 This vulnerability is extremely widespread, as any web application that  Has no authorization checks for vulnerable actions  Will process an action if a default login is able to be given in the request (eg. http://www.example.com/admin/doSomething.php?user=admin&pa ss wd=admin)  Authorizes requests based only on credentials that are automatically submitted such as the session cookie if currently logged into the application, or ―Remember me‖ functionality if not logged into the application, or a Kerberos token if part of an Intranet participating in integrated logon with Active Directory is at risk. Unfortunately, today, most web applications rely solely on automatically submitted credentials such as session cookies, basic authentication credentials, source IP addresses, SSL certificates, or Windows domain credentials. This vulnerability is also known by several other names including Session Riding, One-Click Attacks, Cross Site Reference Forgery, Hostile Linking, and Automation Attack. The acronym XSRF is also frequently used. OWASP and MITRE have both standardized on the term Cross Site Request Forgery and CSRF. A cross-site request forgery (CSRF) vulnerability occurs when: 1. A web application uses session cookies. 2. The application acts on an HTTP request without verifying that the request was made with the user's consent. If the request does not contain a nonce that proves its provenance, the code that handles the request is vulnerable to a CSRF attack (unless it does not change the state of the application.) This means a web application that uses session cookies has to take special precautions in order to ensure that an attacker can't trick users into submitting bogus requests.[5][1] 3.2.4.2 Impact on Web Application If an administrator for the vulnerable site visits a page containing this code while she has an active session, she will unwittingly create an account for the attacker. It is possible because the application does not have a way to
  • 37.
    CHAPTER 3. PROPOSEDWORK 30 determine the provenance of the request. Any request could be a legitimate action chosen by the user or a faked action set up by an attacker. The attacker does not get to see the web page that the bogus request generates, so the attack technique is only useful for requests that alter the state of the application. 3.2.4.3 Example: Figure 3.3: Cross-Site Request Forgery Vulnerability. Above figure 3.3 is showing typical example of cross-site request forgery vulnerablity in which hacker want to get authentication to www.facebook.com through hist server posting parameteres to facebooks server. cross-site request forgery can be done by editing XML script as shown below. var req = new XMLHttpRequest(); req.open("POST", "/new_user", true); body = addToPost(body, new_username); body = addToPost(body, new_passwd); req.send(body); An attacker might set up a malicious web site that contains the following code.
  • 38.
    CHAPTER 3. PROPOSEDWORK 31 var req = new XMLHttpRequest(); req.open("POST", "http://www.example.com/new_user", true); body = addToPost(body, "attacker"); body = addToPost(body, "haha"); req.send(body); Most web browsers send an HTTP header named referrer along with each request. The referrer header is supposed to contain the URL of the referring page, but attackers can forge it, so the referrer header is not useful for determining the provenance of a request. Applications that pass the session identifier on the URL rather than as a cookie do not have CSRF problems because there is no way for the attacker to access the session identifier and include it as part of the bogus request. 3.2.4.4 Recommendations: Applications that use session cookies must include some piece of information in every form post that the back-end code can use to validate the provenance of the request. One way to do that is to include a random request identifier, like this: RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, "/new_user"); body = addToPost(body, new_username); body = addToPost(body, new_passwd); body = addToPost(body, request_id); rb.sendRequest(body, new NewAccountCallback(callback)); Then the back-end logic can validate the request identifier before processing the rest of the form data. When possible, the request identifier should be unique to each server request rather than shared across every request for a particular session. As with session identifiers, the harder it is for an attacker to guess the request identifier, the harder it is to conduct a successful CSRF attack. The token should not be easily guessed and it should be protected in the same way that session tokens are protected. Additional mitigation techniques include:
  • 39.
    CHAPTER 3. PROPOSEDWORK 32  Framework protection: Most of modern web application frameworks include CSRF protection embedded and they will automatically include and verify CSRF tokens.  Use a Challenge-Response control: Forcing the customer to respond to a challenge sent by the server is a strong defense against CSRF. Some of the challenges that can be used for this purpose are: CAPTCHAs, password re-authentication and one- time tokens.  Check HTTP Referrer/Origin headers: An attacked won't be able to spoof these headers while performing a CSRF attack. This makes these headers a useful method to prevent CSRF attacks.  Double-submit Session Cookie: Sending the session ID Cookie as a hidden form value in addition to the actual session ID Cookie is a good protection against CSRF attacks. The server will check both values and make sure they are identical before processing the rest of the form data. If an attacker submits a form in behalf of a user, he won't be able to modify the session ID cookie value as per the same-origin-policy.  Limit Session Lifetime: When accessing protected resources using a CSRF attack, the attack will only be valid as long as the session ID sent as part of the attack is still valid on the server. Limiting the Session lifetime will reduce the probability of a successful attack.[5][1] 3.2.5 Vulnerability - Full Path Disclosure (FPD) 3.2.5.1 Explanation: Many websites running wordpress are exposing the internal path/full path where the php files are installed when they display a php message error. This is not necessary a wordpress issue it‘s a generic php configuration. WordPress developers don‘t see it as a security risk because considering that potential attackers don‘t have access to the internal structure, even if they know it. Which might not be always true considering. It‘s very simple, it just make a request which generates an error message. If the log is not disabled the internal path is displayed in the error message. For
  • 40.
    CHAPTER 3. PROPOSEDWORK 33 wordpress there are many known ways to get a message error. A warning or an error message will be displayed in the page which containing the internal path. 3.2.5.2 Impact on Web Application There is no direct impact; however, this information can help an attacker identify other vulnerabilities or help during the exploitation of other identified vulnerabilities. If the webroot is getting leaked, attackers may abuse the knowledge and use it in combination with file inclusion vulnerabilities to steal configuration files regarding the web application or the rest of the operating system.[1] 3.2.5.3 Example If error reporting is enabled then it displays errors which contains full path of current file. <b>Warning</b>: trim() expects parameter 1 to be string, array given in <b>/home/content/15/10734315/html/multishark/wp- includes/query.php</b> on line <b>2625</b><br /> Figure 3.4: Full Path Disclosure vulnerability. 3.2.5.4 Recommendations: How to hide the wordpress internal path? There is a simple solution to configure the server to disable the display of warnings and error logs. Practically there are 3 options to do that:
  • 41.
    CHAPTER 3. PROPOSEDWORK 34  in the php.ini configuration files  in the .htaccess file, in the root of the wordpress installation  in the php script Disabling Warning and Errors in the php.ini configuration files You have to add any of the following lines: display_errors = 0 display_errors = Off Once you have modified the php.ini file you have to restart the server Disabling Warning and Errors in .htaccess file You have to add any of the following lines: php_flag display_errors off Disabling Warning and Errors in php file You have to add any of the following lines: ini_set('display_errors','Off'); 3.2.6 Vulnerability - Arbitrary code execution 3.2.6.1 Explanation: Developers often directly use or concatenate potentially vulnerable input with file or assume that input files are genuine. When the data is NOT checked properly, this can lead to the vulnerable content being processed or invoked by the web server. Regardless of the language a program is written in, the most devastating attacks often involve remote code execution, whereby an attacker succeeds in executing malicious code in the program's context. If attackers are allowed to upload files to a directory that is accessible from the Web and cause these files to be passed to the PHP interpreter, then they can cause malicious code contained in these files to execute on the server. An attacker can execute arbitrary commands on the system. The web server can be compromised by uploading and executing a web-shell which can run commands, browse system files, browse local resources, attack other servers, and exploit the local vulnerabilities. 3.2.6.2 Example Below are some of the classic examples of :
  • 42.
    CHAPTER 3. PROPOSEDWORK 35 o Upload .php file into web tree. o Upload .gif to be resized. o Upload huge files. o Upload file containing tags. o Upload .exe file into web tree. The function do_upload() in Upload.php calls move_uploaded_file(). Permitting users to upload files can allow attackers to inject dangerous content or malicious code to run on the server. Example 1: The following code processes uploaded files and moves them into a directory under the Web root. Attackers can upload malicious PHP source files to this program and subsequently request them from the server, which will cause them to be executed by the PHP interpreter. <?php $udir = 'upload/'; // Relative path under Web root $ufile = $udir . basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $ufile)) { echo "Valid upload receivedn"; } else { echo "Invalid upload rejectedn"; } ?> Even if a program stores uploaded files under a directory that isn't accessible from the Web, attackers might still be able to leverage the ability to introduce malicious content into the server environment to mount other attacks. If the program is susceptible to path manipulation, command injection, or remote include vulnerabilities, then an attacker might upload a file with malicious content and cause the program to read or execute it by exploiting another vulnerability.[1]
  • 43.
    CHAPTER 3. PROPOSEDWORK 36 Figure 3.5: Arbitrary Code Execution Vulnerability. 3.2.6.3 Recommendations: Unless your program specifically requires its users to upload files, disable the file_uploads option in configuration file. File upload option can be disabled by including the following entry in php.ini: file_uploads = 'off' The file_uploads option can also be disabled by including the following entries in the Apache httpd.conf file: php_flag file_uploads off If a program must accept file uploads, then restrict the ability of an attacker to supply malicious content by only accepting the specific types of
  • 44.
    CHAPTER 3. PROPOSEDWORK 37 content the program expects. Most attacks that rely on uploaded content require that attackers be able to supply content of their choosing and restrictions on this content can greatly limit the range of possible attacks.[1] 3.2.7 Vulnerability - Denial-of-service attack 3.2.7.1 Explanation: Denial of Service (DOS) attack is an attempt by hackers to make a network resource unavailable. It is usually temporary or indefinitely interrupts the host which is connected to the internet. These attacks typically target services hosted on mission critical web servers such as banks, credit card payment gateways.[1] 3.2.7.1.1 Symptoms of DOS Symptoms of Denial of Service attack are given below -  Unusually slow network performance.  Unavailability of a particular web site.  Inability to access any web site.  Dramatic increase in the number of spam emails received.  Long term denial of access to the web or any internet services.  Unavailability of a particular web site. 3.2.7.2 Example Figure 3.6 showing Denial of Service vulnerability in which attacker ping server with huge data which block the network and resource will be unavailable.
  • 45.
    CHAPTER 3. PROPOSEDWORK 38 Figure 3.6: Denial of Service vulnerability. 3.2.7.3 Impact on Web Application In computer network security, backscatter is a side-effect of a spoofed denial-of-service attack. In this kind of attack, the attacker spoofs (or forges) the source address in IP packets sent to the victim. In general, the victim machine cannot distinguish between the spoofed packets and legitimate packets, so the victim responds to the spoofed packets as it normally would. These response packets are known as backscatter.[1] 3.2.7.4 Recommendations:  Use a QoS feature in the load balancer to send all anonymous sessions to separate application servers in your cluster, while logged-on users use another set. This prevents an application-level anonymous DDOS taking out valuable customers  Using a strong CAPCHA to protect anonymous services  Session timeouts  Have a session-limit or rate-limit on certain types of request like reports. Ensure that you can turn off anonymous access if necessary  Ensure that a user has a limit to the number of concurrent sessions (to prevent a hacked account logging on a million times)  Have different database application users for different services (eg transactional use vs. reporting use) and use database resource management to prevent one type of web request from overwhelming all others  If possible make these constraints dynamic, or at least configurable. This way, while you are under attack, you can set aggressive temporary limits in place ('throttling' the attack), such as only one session per user, and no anonymous access. This is certainly not great for your customers, but a lot better than having no service at all.[1] 3.2.8 Memory Exhaustion Vulnerability
  • 46.
    CHAPTER 3. PROPOSEDWORK 39 3.2.8.1 Explanation: Memory Exhaustion is one of the most intractable classes of programming errors, for two reasons: 1. The source of the memory corruption and its manifestation may be far apart, making it hard to correlate the cause and the effect. 2. Symptoms appear under unusual conditions, making it hard to consistently reproduce the error. Memory Exhaustion errors can be broadly classified into four categories: 1. Using uninitialized memory: Contents of uninitialized memory are treated as garbage values. Using such values can lead to unpredictable program behavior. 2. Using none-owned memory: It is common to use pointers to access and modify memory. If such a pointer is a null pointer, dangling pointer (pointing to memory that has already been freed), or to a memory location outside of current stack or heap bounds, it is referring to memory that is not then possessed by the program. Using such pointers is a serious programming flaw. Accessing such memory usually causes operating system exceptions, that most commonly lead to a program crash (unless suitable memory protection software is being used). 3. Using memory beyond the memory that was allocated (buffer overflow): If an array is used in a loop, with incorrect terminating condition, memory beyond the array bounds may be accidentally manipulated. Buffer overflow is one of the most common programming flaws exploited by computer viruses, causing serious computer security issues (e.g. return-to-libc attack, stack-smashing protection) in widely used programs. In some cases programs can also incorrectly access the memory before the start of a buffer. 4. Faulty heap memory management: Memory leaks and freeing non-heap or un-allocated memory are the most frequent errors caused by faulty heap memory management.[6] 3.2.8.2 Example
  • 47.
    CHAPTER 3. PROPOSEDWORK 40 Figure 3.7: Memory Exhaustion vulnerability. 3.2.8.3 Recommendations:  Use a QoS feature in the load balancer.  Strong Garbage Collection Handling.  Reuse of free locations.  Use of safe libraries  Pointer protection  Executable space protection  Deep Testing  Corruption Protection 3.2.9 Vulnerability - File Inclusion 3.2.9.1 Explanation: Situation described below is typical file injection vulnerability and in this situation, without filtering request data, you are vulnerable both for Local File Injection (LFI) and Remote File Injection (RFI).[3] It's also good to remember that: 1. include or require will load and execute any good code in php wheter it is in php file or not. Look here for example of jpg image carring php code (and this file is even rocognized as image/jpg by mimetype!). 2. include or require will also open plain text files, like your etc/hosts without errors if you are working on default Apache/PHP settings. 3. With GET varialbe like yours, in Windows, end user can just use variable with ".." path. So it is possible to check all dirs loosely. 4. Here you can check how you can include remote files. Based on answers there you can easily reconfigure your server/php stack and test vulnerability.
  • 48.
    CHAPTER 3. PROPOSEDWORK 41 3.2.9.2 Example Figure 3.8: File Inclusion vulnerability. Figure showing an attacker to include and execute a remotely hosted file using a script by including it in the attack page. The attacker can use RFI to run a malicious code either on the client side or on the server.[3] 3.2.9.3 Impact on Web Application File inclusion vulnerability allows an attacker to access unauthorized or sensitive files available on the web server or to execute malicious files on the web server by making use of the ‗include‘ functionality. The impact of this vulnerability can lead to malicious code execution on the server or reveal data present in sensitive files, etc.[3] 3.2.9.4 Recommendations: Information we can conclude that the file inclusion attacks can be at times more harmful than SQL injection, etc — therefore there is a great need to remediate such vulnerabilities. And proper input validation is the only key to avoid such vulnerabilities.[3][5] File Inclusion Vulnerability can be avoided by taken care of following points:  In most cases removal of special characters from variable used to include files is enough to prevent successful exploitation.  Blacklist all the special characters which are not of any use in a filename.  Web Application Firewall can be an efficient solution to prevent vulnerability exploitation  Limit the API to allow inclusion of files only from one allowed directory so that directory traversal can also be avoided.  create a rule that allows only alphabetical characters
  • 49.
    CHAPTER 3. PROPOSEDWORK 42 3.2.10 Vulnerability - HTML Injection 3.2.10.1 Explanation: HTML injection is an attack that is similar to Cross-site Scripting (XSS). While in the XSS vulnerability the attacker can inject and execute Javascript code, the HTML injection attack only allows the injection of certain HTML tags. When an application does not properly handle user supplied data, an attacker can supply valid HTML code, typically via a parameter value, and inject their own content into the page. This attack is typically used in conjunction with some form of social engineering, as the attack is exploiting a code-based vulnerability and a user's trust.[6][7][8] A possible attack scenario is demonstrated below:  Attacker discovers injection vulnerability and decides to use an HTML injection attack  Attacker crafts malicious link, including his injected HTML content, and sends it to a user via email  The user visits the page due to the page being located within a trusted domain  The attacker's injected HTML is rendered and presented to the user asking for a username and password  The user enters a username and password, which are both sent to the attackers server 3.2.10.2 Example Figure 3.9: HTML Injection vulnerability.
  • 50.
    CHAPTER 3. PROPOSEDWORK 43 3.2.10.3 Impact on Web Application A malicious attacker can exploit the users of this application if he set up a page that is capturing their cookies and credentials in his server. If he has this page then he can trick the users to enter their credentials by injecting into the vulnerable page a fake HTML login form. Thus the attacker retains control of the script and can update or remove the exploit code at anytime. [6][7] 3.2.10.4 Recommendations:  Your script should filter metacharacters from user input.  mysql_real_escape_string used when insert into database  htmlentities() used when outputting data into webpage  htmlspecialchars / entities encode the special chars, so they're displayed but not interpreted. strip_tags REMOVES them. 3.2.11Other Vulnerabilities 3.2.11.1 Vulnerability- Dangerous Function 3.2.11.1.1 Explanation: The function mysql_escape_string() cannot be used safely. It should not be used. Certain functions behave in dangerous ways regardless of how they are used. Functions in this category were often implemented without taking security concerns into account. $str = mysql_escape_string($str); In this case the dangerous function you are using is mysql_escape_string() The mysql_escape_string() function is unsafe as it does not take into consideration the current character encoding set within the database. It can thus be vulnerable to multi-byte escaping issues. mysql_escape_string() also does not escape the '%' and '_' characters.[7] 3.2.11.1.2 Example HTML markup could be inserted into your DB and used for Cross Site Scripting attacks. Harmful Code:- <?php elseif (function_exists('mysql_escape_string')) { $str = mysql_escape_string($str); }
  • 51.
    CHAPTER 3. PROPOSEDWORK 44 $item = "Zak's % L o _Laptop"; $escaped_item = mysql_escape_string($item); printf("Escaped string: %sn", $escaped_item); ///Output : Zak's % L o _Laptop ?> 3.2.11.1.3 Recommendations: Functions that cannot be used safely should never be used. If any of these functions occur in new or legacy code, they must be removed and replaced with safe counterparts. mysql_escape_string() function has been deprecated as of PHP 5.3.0. It has been replaced with mysql_real_escape_string(). It is recommended that untrusted data be passed to the function within a single quote delimited value, cast to a numeric type or convert the value to a numeric type. [7] Secure Code:- <?php //Using quote limited values with mysql_real_escape_string $db->query("DELETE FROM table WHERE col1='{mysql_real_escape_string($_GET['ID'])}'); //Casting to a numeric type $db->query("DELETE FROM table WHERE col1=". (int) $_GET['ID'] .");" //Explicitly converting to a numeric type $db->query("DELETE FROM table WHERE col1=". intval($_GET['ID']) .");" ?> 3.2.11.2 Vulnerability- Key Management: Hardcoded Encryption Key Hardcoded encryption keys could compromise system security in a way that cannot be easily remedied. 3.2.11.2.1 Explanation: It is never a good idea to hardcode an encryption key. Not only does hardcoding an encryption key allow all of the project's developers to view the encryption key, it also makes fixing the problem extremely difficult. Once the code is in production, the encryption key cannot be changed without patching the software. If the account protected by the encryption key is compromised, the owners of the system will be forced to choose between security and availability.[8]
  • 52.
    CHAPTER 3. PROPOSEDWORK 45 3.2.11.2.2 Example The following code uses a hardcoded encryption key to encrypt information: <?php $encryption_key = 'hardcoded_encryption_key'; //$filter=new Zend_Filter_Encrypt('hardcoded_encryption_key'); $filter = new Zend_Filter_Encrypt($encryption_key); $filter->setVector('myIV'); $encrypted = $filter->filter('text_to_be_encrypted'); print $encrypted; ?> This code will run successfully, but anyone who has access to it will have access to the encryption key. Once the program has shipped, there is no going back from the hardcoded encryption key ('hardcoded_encryption_key') unless the program is patched. A devious employee with access to this information can use it to compromise data encrypted by the system.[8] 3.2.11.3 Impact on Web Application Hardcoding an encryption key allow all of the project's developers to view the encryption key, it also makes fixing the problem extremely difficult. Once the code is in production, the encryption key cannot be changed without patching the software. 3.2.11.3.1 Recommendations: Encryption keys should never be hardcoded and should generally be obfuscated and managed in an external source. Storing encryption keys in plaintext anywhere on the system allows anyone with sufficient permissions to read and potentially misuse the encryption key. 3.2.11.4 Vulnerability- Password Management: Hardcoded Password Hardcoded passwords could compromise system security in a way that cannot be easily remedied.[11] 3.2.11.4.1 Explanation: It is never a good idea to hardcode a password. Not only does hardcoding a password allow all of the project's developers to view the password, it also makes
  • 53.
    CHAPTER 3. PROPOSEDWORK 46 fixing the problem extremely difficult. Once the code is in production, the password cannot be changed without patching the software. If the account protected by the password is compromised, the owners of the system will be forced to choose between security and availability.[9][11] 3.2.11.4.2 Example The following code uses a hardcoded password to connect to a database: <?php $link = mysql_connect($url, 'scott', 'tiger'); if (!$link) { die('Could not connect: ' . mysql_error()); } ?> This code will run successfully, but anyone who has access to it will have access to the password. Once the program has shipped, there is no going back from the database user "scott" with a password of "tiger" unless the program is patched. A devious employee with access to this information can use it to break into the system. 3.2.11.4.3 Impact Hard coding a password allow all of the project's developers to view the password, it also makes fixing the problem extremely difficult. Once the code is in production, the password cannot be changed without patching the software.[11] 3.2.11.4.4 Recommendations: Passwords should never be hardcoded and should generally be obfuscated and managed in an external source. Storing passwords in plaintext anywhere on the system allows anyone with sufficient permissions to read and potentially misuse the password. 3.2.11.5 Vulnerability- Path Manipulation (Input Validation and Representation, Data Flow) Attackers can control the filesystem path argument to file(), which allows them to access or modify otherwise protected files. $tmp = file($dir . 'php_' . $name . '.afm');
  • 54.
    CHAPTER 3. PROPOSEDWORK 47 $this->fonts[$font] = unserialize($tmp[0]); 3.2.11.5.1 Explanation: Path manipulation errors occur when the following two conditions are met: 1. An attacker can specify a path used in an operation on the filesystem. 2. By specifying the resource, the attacker gains a capability that would not otherwise be permitted. Harmful Code:- <?php $filename = $CONFIG_TXT['sub'] . ".txt"; $handle = fopen($filename,"r"); $amt = fread($handle, filesize($filename)); echo $amt; ?> 3.2.11.5.2 Recommendations: It is always a good programming practice that validates the path or file name before using it. Secure Code:- <?php $filename = $CONFIG_TXT['sub'] . ".txt"; $handle = fopen(getValidFile($filename),"r"); $amt = fread($handle, filesize($filename)); echo $amt; ?> 3.2.11.6 Vulnerability- Hidden Field 3.2.11.6.1 Explanation: Programmers often trust the contents of hidden fields, expecting that users will not be able to view them or manipulate their contents. Attackers will violate these assumptions. They will examine the values written to hidden fields and alter them or replace the contents with attack data.[9][10] 3.2.11.6.2 Example
  • 55.
    CHAPTER 3. PROPOSEDWORK 48 An <input> tag of type hidden indicates the use of a hidden field. <input type="hidden"> If hidden fields carry sensitive information, this information will be cached the same way the rest of the page is cached. This can lead to sensitive information being tucked away in the browser cache without the user's knowledge.[9][10] 3.2.11.7 Impact on Web Application Browsers add-ons like firebug, inspect element etc allows attacker to get the value of hidden field and manipulate it. Hidden sensitive information can lead to disclouser of crucial information. 3.2.11.8 Recommendations: Expect that attackers will study and decode all uses of hidden fields in the application. Treat hidden fields as untrusted input. Don't store information in hidden fields if the information should not be cached along with the rest of the page.[9][10] 3.2.11.9 Vulnerability - Often Misused: File Upload (Input Validation and Representation, content) Do not allow file uploads if they can be avoided. If a program must accept file uploads, then restrict the ability of an attacker to supply malicious content by only accepting the specific types of content the program expects. Most attacks that rely on uploaded content require that attackers be able to supply content of their choosing. Placing restrictions on the content the program will accept will greatly limit the range of possible attacks. Check file names, extensions, and file content to make sure they are all expected and acceptable for use by the application.[8][11] 3.3 Good Programming practices 3.3.1 Avoid short tags If Short tags are disabled on some server, then all of a sudden the whole php code will be displayed even before you are informed about it. <?= $a = 5;
  • 56.
    CHAPTER 3. PROPOSEDWORK 49 ?> This will run fine when short codes are enabled, but when not, the whole code will be dumped to the browser.All input coming from the user , in the form of POST and GET must be validated to be acceptable by the application logic.  Check the 'type' of the data  Check range of numbers  Check length of strings  Check emails , urls , dates to be valid  Ensure that data does not contain unallowed characters. 3.3.2 Always name your file as only .php Although this is a not very significant to mention point, but still there have been instances of this particular security flaw. Ensure that all php code files have the extension ".php". Let‘s say the database credentials are stored in a separate configuration file and that the file has been named as 'config.inc'. <?php /*Database connection details*/ $db_host = 'localhost'; $db_user = 'project'; $db_pass = 'secret'; $db_name = 'project_ecommerce'; ?> Now if this file is opened in the browser, the contents will be displayed right away. Hence never name your files to anything else except ‗.php‘. 3.3.3 Salt the passwords and use stronger encryption Md5 is a very popular encryption algorithm/function being used by php developers. The md5 function gives the hash rightaway. <?php $hash = md5($password); ?> However md5 is not a fully secure way to store passwords. Most users tend to keep a 5-8 character password, and whatever be the complexity of such a password, it can be easily cracked by just brute forcing on a normal computer/pc.
  • 57.
    CHAPTER 3. PROPOSEDWORK 50 Moreover even brute forcing might not be necessary, just typing the hash on google.com would reveal the password on some password cracking/rainbow table website. Although users are repeatedly told to keep a strong password its not enough. To overcome this problem developers often use "salt". The add some more text to the password before hashing it and then do the same when comparing user provided password. <?php $salt = 'SUPER_SALTY'; //Any random non-predictable string $hash = md5($password . $salt); ?> Adding a salt increases the length of the password, and hence its complexity. So the time required for a brute force program to crack it increase by a huge span. Along with salt, its a good practice to use a longer(slower) hash algorithm like sha1, sha2 etc. The slower the hashing algorithm, more the time required by a brute force program and hence better the strength. Bcrypt encryption is even more complex than the sha algorithm and considered more secure. Check the php crypt function.[11] 3.3.4 Regenerate Session ID It is a good idea to regenerate the session id at specific events or intervals. It might help if the earlier session id was hacked. To regenerate the session id use the following function <?php session_regenerate_id(); //changes only session id //or session_regenerate_id(true); ?> The session id should be regenerated atleast when authentication levels change, for example when  a user logs in  a user logs out  a user gets administrative access or change of privilege happens. <?php if(valid_username() and valid_password())
  • 58.
    CHAPTER 3. PROPOSEDWORK 51 { $_SESSION['logged'] = true; $_SESSION['username'] = $username; } ?> You may even want to regenerate session id every 15 minutes or every 100 requests. <?php session_start(); //increment and check if ( ++$_SESSION['regenerated_count'] > 100 ) { //reset and regenerate $_SESSION['regenerated_count'] = 0; session_regenerate_id(true); } ?> 3.3.5 Store sessions in database By default sessions are stored in files. Many applications are hosted on shared hosting environments where the session files are saved to /tmp directory. Now this directory may be readable to other users. If unencrypted the session information will be plain text in the file : userName|s:5:"ngood";accountNumber|s:9:"123456789"; There are many workarounds for this. Encrypt the session information with suhosin. Store sessions in database. Sessions stored inside database are not visible like files. They are only available to the application using it. 3.3.6 Force single session For a higher level of security, make sure that a user is not logged in from 2 locations at a time. If user try to login from another location, first logout from the previous login. This is useful on websites that exchange confidential data. for example an online banking website. This is easy to implement when sessions are saved in database. Simply delete any previous login record of a username on every login.[7] 3.3.7 Configure the database user with care Make sure the database user does not have privileges to execute command or write to local filesystem. If there is an sql injection vulnerability
  • 59.
    CHAPTER 3. PROPOSEDWORK 52 somewhere in the website and the database user has write privileges, then this is sufficient for a hacker to take over the server completely just by using simple tool like sql map. So the permissions of the database user should be set according to needs. It is a good idea to have a separate user for use by the web application that has only the minimal required privileges on the database system. Or have separate database users for viewing and modifying the database.[11] 3.3.8 Disable directory content listing Using htaccess Putting the following the .htaccess file shall disable directory listing. Options -Indexes Using index.html If the server does not allow this, then the easiest way is to put a dummy index.html file in all directories. So that when directory path is accessed, the index.html will open up.[9] 3.3.9 Keep resources outside WEB_ROOT When hosting applications on a server, the path is generally like this : /var/www/ OR /home/username/www/ All web content is kept inside www , then only it is accessible on a website. But those contents which are not meant to be directly accessible from a url , can be kept outside the /www. For example uploaded images , or resource files , or files containing database connection parameters or anything. php files to be called by browser in /var/www/ Other resource files in /var/outside/ By doing this the files automatically become invisible to outside world even if directory listing is enabled.[9] 3.3.10 Upload files to a location outside webroot Applications that allow users to upload files can put the uploaded files in a location that is outside the web root. This can help in a situation of arbitrary file upload. If a hacker were to find such a vulnerability he would try to upload a shell script and execute it by triggering from the browser. Now if the file is
  • 60.
    CHAPTER 3. PROPOSEDWORK 53 outside the web root, then even if the hacker would know the path to the file, it would be harder for him to execute the shell.[10] 3.3.1115. Disable display_errors in your php.ini file Do not wait to turn off display_errors in your php script using ini_set or htaccess or anything similar. Compilation errors that occur before execution of the script starts will not obey any script rules and would be displayed right away. Hence display of errors should be disabled right in the php.ini file in production environment. 3.3.12 Setup correct directory permissions in the production environment Directories should have proper permissions with regard to the need of being writable or not. Keep a separate directory for temp files, cache files and other resource files and mark them writable as needed. Everything else like the directory containing core application code, library files etc should be unwritable. Also directories (like temp) which can contain resource files, or files with other information should be guarded well and be totally inaccessible to the outside web. Use htaccess to block all access to such directories deny from all.[10][11]
  • 61.
    CHAPTER 4. PLATFORMOF RESEARCH 54 Chapter 4 Platform of Research Security of web application is an important issue should be taken care by every organization. Security of data and information available is most important. Security Audit of a web application improves the protection by showing the possible threads available by fixing those threads it will be nearly robust. It improves the performance of existing web application. Many testing tools free as well as paid are available. More secure web application attracts more people and provide service guarantee which is the first requirement of a web application these days. The thesis is analyzed from various testing reports testing tools and security audit trails experiments, those were conducted using following tools, add-on and software: Server-Side Script: PHP Client side Script: Javascript Database: Mysql Browser: Mozila Firefox Operating System: Microsoft Windows 7 Professional (64 bit) Add-On: Firebug, Selenium S/w Tools: Burp Suit, Fortify Testing Tool, Acunetix Vulnerability Scanner, DirBuster and other testing tools.
  • 62.
    CHAPTER 5. CONCLUSIONAND FUTURE WORK 54 Chapter 4 Platform of Research Security of web application is an important issue should be taken care by every organization. Security of data and information available is most important. Security Audit of a web application improves the protection by showing the possible threads available by fixing those threads it will be nearly robust. It improves the performance of existing web application. Many testing tools free as well as paid are available. More secure web application attracts more people and provide service guarantee which is the first requirement of a web application these days. The thesis is analyzed from various testing reports testing tools and security audit trails experiments, those were conducted using following tools, add-on and software: Server-Side Script: PHP Client side Script: Javascript Database: Mysql Browser: Mozila Firefox Operating System: Microsoft Windows 7 Professional (64 bit) Add-On: Firebug, Selenium S/w Tools: Burp Suit, Fortify Testing Tool, Acunetix Vulnerability Scanner, DirBuster and other testing tools.
  • 63.
    CHAPTER 5. CONCLUSIONAND FUTURE WORK 55 Chapter 5 Conclusion and Future Work 4.1 Conclusion This dissertation presents some basic and advanced methods to understand and prevent web attacks and other vulnerabilities like XSS,SQL Injection, input validation based attacks in a meta programming setting, the domain of web applications. This dissertation describes the first formal, realistic characterization of SQL injection, XSS and other vulnerabilities and presents principled, practical analyses for identifying vulnerabilities and preventing attacks. The analyses can detect and block real attacks and uncover unknown vulnerabilities in real-world code. We studied many existing approaches to detect and prevent these vulnerabilities in an application, giving a brief note on their advantages and disadvantages. All the approaches followed by different methods leads to a very interesting solution; however some failures are associated with almost each one of them at some point. Furthermore these scanners support all web applications, many of them supports only for PHP web applications with known vulnerabilities. We began with a formal definition of Attacks and Vulnerabilities with most common security attacks such as XSS, SQL injection, HTML Injection, etc., those are based on data integrity and sentential forms. Initially, we proposed the first principled definition of XSS injection by explainting the effect and impact with prevention techniques. That untrusted input is permitted to have on SQL queries that a web application constructs. Our characterization employs two primary notions: sentential forms, an abstraction from parsing algorithms used in compilers; and integrity, a fundamental concept in security that forbids untrusted
  • 64.
    CHAPTER 5. CONCLUSIONAND FUTURE WORK 56 data from modifying trusted data. Our definition provides a solid foundation for prevent attacks. Basics and advance methods to check for attacks and vulnerabilities. 4.2 Future Work - Develop a GUI for the scanner script, so make it easy for anyone to install and use the scanner. - Add full support for all known vulnerabilities for all platform XSS detection techniques which should be platform independent. - Implement a local proxy module to be included in the scanner work, which will make a full vulnerability analysis environment.