background

Some time ago, when I was working, the safety students specially reminded me to pay attention to safety problems, such as:

  • High concurrency security issues (high concurrency generated by repeated lottery, repeated points, repeated participation in activities, repeated XXX issues).
  • SMS receiving risk control security issues (loss of SMS costs is a problem, but the most concerned is that SMS is brushed up to affect the use of business).
  • Asset retention content XSS attack displayed at the back end (attacked from the asset retention entry into the Intranet background).
  • The system ofPersonal centerUnauthorized loopholes (unauthorized view of personal address, unauthorized claim, unauthorized order, unauthorized invoice and other data)

Frankly speaking, there is little concern about security, so I communicated with students about security and recommended a book called White Hat on Web security. The content of this paper is modified based on the introduction of this book.

Books information

Full name of this book: White Hat on Web Security author: Wu Hanqing Publishing House: Publishing House of Electronics Industry edition: January 2015

The three elements of security

  • Confidentiality, which requires the protection of data content from disclosure, encryption is a common means to achieve confidentiality requirements.
  • Integrity requires the protection of data content is complete and has not been tampered with. Digital signature is a common technical means to ensure consistency.
  • availabilityIs required to protect resourcesOn demand.

Safety assessment Process

It can be briefly divided into four stages:

  • Asset class classification.
  • Threat analysis.
  • Risk analysis.
  • Identify the solution.

Asset class division

  • The core of the Internet is driven by user data. Users generate business and business generates data. Therefore, the core issue of Internet security is data security.
  • Different businesses have different emphases, so when dividing assets, it is necessary to communicate with each business to understand the most important assets and data of the company.
  • After knowing the target to be protected, you need to divide the trust domain and trust boundary. For example, can two applications be trusted when transmitting data? Whether there should be a boundary and security checks on the data.

Threat analysis

Threat analysis is to find out all the threats, usually by brainstorming. However, most of them will adopt threat modeling to list as many risks as possible, with the advantage of avoiding omission. The commonly used method is called STRIDE model, as follows:

It mainly includes disguise, tampering, denial, information disclosure, denial of service and promotion of authority.

Risk analysis

The risk consists of the following factors:

Risk = Probability * Damage Potential
Copy the code

In addition to the loss caused, the risk can be correctly judged by weighing the possibility of the event.

DREAD model proposed by Microsoft can judge the risk degree of threat more scientifically:

Features of security solutions

A good security solution should have the following characteristics:

  • Able to solve problems effectively.
  • Good user experience.
  • High performance.
  • Low coupling.
  • Easy to expand and upgrade.

The method of designing the scheme

  • Blacklist and whitelist, such as opening only one port.
  • The principle of minimum permissions, granting only necessary permissions to principals, reduces the chance of errors.
  • The principle of defense in depth provides an overall solution to the system from different levels and angles.
  • Separation of data and code to prevent security issues due to injection.
  • The principle of unpredictability prohibits the use of regular features such asId =1, 2, and 3Incrementing, it is recommended to use encryption algorithms, random number algorithms, hash algorithms to provide unpredictability.

Browser security

The same-origin policy

Web page B cannot be opened unless the two web pages are “homologous”. “Homology” means “three of the same”. The definition is as follows:

Same protocol same domain name same port sameCopy the code

For example, http://www.jb.com/dir/page.html, the agreement is http://, a domain name is www.jb.com, port is 80, and its homologous situation is as follows.

Homologous homologous http://www.jb.com/dir/inner/another.html: http://www.jb.com/dir2/other.html: http://jb.com/dir/other.html: Different source (domain name) different source http://v2.www.jb.com/dir/other.html: (domain name) different source http://www.jb.com:81/dir/other.html: (port)Copy the code

Imagine A situation where A user logs on to site A and then goes to Site B. What happens if Website B can read the Cookie of Website A?

Obviously, if a Cookie contains privacy (such as amounts, personal information, etc.), that information will be disclosed.

Therefore, the purpose of the same-origin policy is to ensure the security of user information and prevent malicious websites from stealing data.

Browser sandbox

Sandbox modeling is a component-relationship design pattern for security in browsers and other applications. It is generally designed to allow untrusted code to run in an environment that restricts untrusted code from accessing resources outside the quarantine zone.

Malicious URL blocking

The way it works is that the browser periodically gets an updated list of malicious urls from the server and pops up a warning page if a user visits a site on the blacklist.

Cross-site scripting (XSS)

An XSS attack usually refers to an attack in which hackers tamper with web pages through HTML injection and insert malicious scripts to gain control of users’ browsers while they browse.

example

One day, the company needs a search page and determines the content of the keywords based on the URL parameters. Jb quickly put the page up and running, with the following code:

<input type="text" value="<%= getParameter("keyword") % >"<%= getParameter() </button> <div>"keyword") %>
</div>

Copy the code

However, shortly after going live, I received a mysterious link from the security team:

http://xxx/search?keyword="><script>alert('XSS'); </script>Copy the code

With a sense of foreboding, I clicked the link and a dialog box popped up that said “XSS”.

When the browser requests http://xxx/search? keyword=”>, spliced into HTML and returned to the browser. The following HTML is formed:

<input type="text" value=""><script>alert('XSS'); </script> 
      
><script>alert('XSS'); </script> </div>Copy the code

is malicious code, so it is executed.

Not only is the content of the div injected, but the value property of the input is injected, and alert pops up twice.

nature

Malicious code is unfiltered and mixed in with the site’s normal code; Browsers cannot tell which scripts are trusted, causing malicious scripts to be executed.

classification

Storage type

Storage XSS will store user input data on the server side, with strong stability.

Attack steps:

  • The attacker submits malicious code to the database of the target website.
  • When the user opens the target website, the website server takes the malicious code out of the database, splices it into HTML and returns it to the browser.
  • When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
  • Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.
  • This kind of attack is common in website functions with user-saved data, such as forum posts, product reviews, and user messages.

reflective

By reflecting the user’s input back to the browser, hackers often need to trick the user into clicking on a malicious link to succeed.

Attack steps:

  • The attacker constructs a special URL that contains malicious code.
  • When a user opens a URL with malicious code, the web server takes the malicious code out of the URL, splices it into HTML and returns it to the browser.
  • When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
  • Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.

The difference between reflex and memory

  • Stored XSS malicious code is stored in the database, reflective XSS malicious code is stored in the URL.
  • Reflective XSS vulnerabilities are common in functions that pass parameters through urls, such as website search, jump, etc.

The DOM model

XSS formed by modifying the DOM node of the page is called DOM Based XSS.

Attack steps:

  • The attacker constructs a specialURL, which contains malicious code.
  • The user opens with malicious codeURL.
  • The user browser receives the response and parses it to the front endJavaScriptTake out theURLAnd execute the malicious code.
  • Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.

Differences between the first two:

  • DOMXSSIn an attack, fetching and executing malicious code is done on the browser side,The DOM is a security hole in the front-end JavaScript itselfAnd the other twoXSSThis is a security vulnerability on the server.

The prevention of

XSS attacks have two main elements:

  • The attacker submits malicious code.
  • The browser executes malicious code.

The input filter

Common Web vulnerabilities, such as XSS and SQL Injection, require the attacker to construct some special characters. These special characters may not be used by normal users, so the existence of input check is necessary.

The logic for input checking must be implemented in server-side code. If you just use JavaScript on the client side for input checking, it’s easy for an attacker to bypass.

A common practice in Web development today is to implement the same input checking in both client-side JavaScript and server-side code. The input check of JavaScript on the client side can prevent most normal users from misoperating, thus saving server resources.

Output filter

When a variable is output to an HTML page, it can be encoded or escaped to defend against XSS attacks.

Cross-site Request Forgery (CSRF)

Cross-site Request Forgery (CSRF) : An attacker induces the victim to access a third-party website and sends cross-site request to the attacked website. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.

Attack process

  • Victim logina.comAnd retained the login credentials (Cookie).
  • The attacker lured the victim to visitb.com.
  • b.coma.comA request was sent:a.com/act=xx. Browsers carry it by defaulta.comtheCookie.
  • a.comUpon receipt of the request, the request is validated and identified as the victim’s credentials, mistaking it for a request sent by the victim himself.
  • a.comExecuted on behalf of the victimact=xx.
  • The attack is complete, the attacker impersonates the victim without the victim’s knowledge, and letsa.comThe user-defined operation is performed.

Attack types

  • getType, request one directlyurlCan.
  • postType, automatically submit the form after accessing the link, simulation complete onepostOperation.
  • Compared with the above two types of links, the cost is higher and users need to click the link to trigger the attack. This type of link is usually embedded malicious links in the pictures published in the forum, or induced users to be lured in the form of advertisements. Attackers usually use exaggerated words to trick users into clicking.

The characteristics of

  • Attacks are generally launched on third party sites, not the site being attacked. The attacked site cannot prevent the attack from happening.
  • Attack using the victim’s login credentials in the attacked website, posing as the victim to submit operations; Instead of stealing data directly.
  • The attacker does not obtain the victim’s login credentials during the whole process, but just uses them.
  • Cross-site requests can be made in a variety of ways: imagesURL, hyperlinks,CORS,FormSubmit and so on. Part of the request can be directly embedded in third-party forums, articles, difficult to track.

Protection strategy

  • Captcha, which forces users to interact with the application, can deter attacks, but only in a secondary form.
  • Referer CheckIs used to check whether the request is coming from a legitimate source, but most request headers can now be customized, so only in auxiliary form.
  • TokenThis is the current accepted practice of the page, as detailed below.

Token

As mentioned above in CSRF, attackers cannot directly steal user information (cookies, headers, website content, etc.), but only use the information in cookies.

The CSRF attack succeeds because the server mistook the request sent by the attacker for the user’s own request. You can then require all user requests to carry a Token that a CSRF attacker cannot obtain. By verifying whether the request carries the correct Token, the server can distinguish the normal request from the attack request and defend against CSRF attacks.

  • willCSRF TokenOutput to the page.
  • The request submitted by the page carries thisToken.
  • Server authenticationTokenIs it correct?

The Token value must be randomly generated.

Click on the hijacked

Clickjacking is a form of visual deception. The attacker uses a transparent, invisible IFrame to overlay a web page and then trick the user into doing something on that page, where the user unknowingly clicks on the transparent IFrame page.

jb.html

Users think they are clicking on the lower content of the page, but what they are really working on is the transparent layer above. And because it’s transparent, the real intention is that the attacker is in control.

Injection safety

introduce

Injection security is probably the most common attack method in the security field, and the general test students are also concerned about this kind of attack. The XSS submitted earlier is also an injection attack on HTML.

The essence of an injection attack is to execute data entered by the user as code.

Key conditions:

  • The first is that the user can control the input.
  • The second is the code that the program is supposed to execute, concatenating the data entered by the user.

SQL injection

example

Here’s the logic:

var Shipcity;
ShipCity = Request.form ("ShipCity");
var sql = "select * from OrdersTable where ShipCity = '" + ShipCity + "'";
Copy the code

The value of the ShipCity variable is submitted by the user. Normally, if the user typed Beijing, the SQL statement would execute:

SELECT * FROM OrdersTable WHERE ShipCity = 'Beijing'
Copy the code

But suppose the user enters a SQL statement with semantics, such as:

Beijing'; drop table OrdersTable--
Copy the code

The SQL statement would actually execute as follows:

SELECT * FROM OrdersTable WHERE ShipCity = 'Beijing'; drop table OrdersTable--'Copy the code

Here you can see that the normal query statement is now executed after the query, and then execute a drop table operation, and this operation is the result of the user to construct malicious data.

Aggressive behavior

Guess the name of the database and back up the database. 2. Guess the name of the field. Query the database permission of the current user. 5. Set a new database account to obtain the database administrator account permission. Obtaining an operating system administrator account using stored procedures 7. Client script attack: Malicious scripts are submitted to the database through normal input and submission methods. When other users browse the content, malicious scripts are attacked. 8. Client script attack: Malicious scripts are submitted to the database through SQL injection and the SQL syntax is directly used to UPCopy the code

How to defense

Precompile and bind variables using SQL statements
 String sql = "select id, no from user where id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, id);
        ps.executeQuery();
Copy the code

As shown above, variables are typically precompiled and bound using SQL statements. Why does this prevent SQL injection?

SQL statement: “Select ID, no from user where id=? Pre-compiled, that is, the SQL engine preanalyzes the syntax, generates the syntax tree, and generates the execution plan.

The following parameters, whatever they are entered, do not affect the syntax structure of the SQL statement because parsing has already been done,and parsing mainly involves parsing SQL commands such as SELECT, FROM, WHERE,and, or,order BY, etc.

So even enter the SQL commands, behind will not be as SQL commands to perform, because these SQL command execution, must first through the syntax analysis, generate execution plan, since the syntax analysis is complete, has been prepared, so behind the input parameters, it is absolutely impossible as SQL commands to perform, Is treated only as a string literal argument. So SQL statement precompilation can protect against SQL injection.

Use safety functions

There are scenarios where string concatenation is necessary, where the data types of parameters need to be strictly checked, and security functions can be used to prevent SQL injection.

The use of security functions, such as:

        MySQLCodec codec = new MySQLCodec(Mode.STANDARD);
        name = ESAPI.encoder().encodeForSQL(codec, name);
        String sql = "select id,no from user where name=" + name;
ESAPI.encoder().encodeForSQL(codec, name)
Copy the code

This function encodes some special characters contained in name so that the SQL engine does not parse the string in name as if it were an SQL command.

Checking data types

SQL =” select id,no from user where id=” + id;

When we receive a parameter from the user, we strictly check the ID, which must be an int. Complications can be determined using regular expressions. This also prevents SQL injection.

XML injection

XML is a common markup language. It represents data structurally through tags, and attacks must meet two conditions:

  • The user can control the input of data.
  • The program successfully pieced together the data.

The solution is similar to the above, just escape the reserved characters contained in the user input data.

Code injection

Code injection and command injection are often caused by unsafe functions or methods.

Against code injection and command injection, you need to disable functions such as eval() and system() that can execute commands. If you must use these functions, you need to process the user’s input data.

Code injection is often the result of unsafe programming practices, and the use of dangerous functions should be avoided as much as possible. It is possible to specify in the development specification which functions are prohibited.

summary

Understand the security assessment process, principles of XSS, CSRF, SQL injection attacks, and common prevention measures, and click the information about common methods of hijacking.

To be continued…