Web security for Web practitioners is a very important topic, so here to summarize the Web related security knowledge, hope not to step on thunder in the future, but also hope to see this article to help students. The main content of this article today is to analyze several common types of attack and defense methods.

Perhaps you have a certain understanding of all the security issues, but the most important thing is to keep the security strings tight in the process of coding design, need to repeatedly review every implementation detail, security is no small matter.


This article is based on node.js code Demo, other server-side languages can also refer to.

XSS

Let’s start with the most common XSS vulnerability, XSS (Cross Site Script), a cross-site scripting attack that can only be called XSS because its acronym overlaps with CSS (Cascading Style Sheets).

The principle of XSS is that malicious attackers insert malicious executable Web script codes into Web pages. When users browse the page, the script codes embedded in the Web will be executed, so that attackers can steal user information or other purposes of violating users’ security and privacy. XSS attacks vary widely, but can be roughly broken down into several types.

Non-persistent XSS

Non-persistent XSS vulnerability, also known as reflective XSS vulnerability, generally sends URL with malicious script code parameters to others. When the URL address is opened, the specific malicious code parameters are parsed and executed by HTML.

For example, let’s say your Web page contains the following code:

Select your language:
<select>
    <script>
        document.write(''
            + '<option value=1>'
            +     location.href.substring(location.href.indexOf('default=') + 8)
            + '</option>'
        );
        document.write('<option value=2>English</option>');
    </script>
</select>Copy the code

An attacker can use the URL directly (similar to: xx.com/xx?default=…) Inject executable script code.

Non-persistent XSS vulnerability attacks have the following characteristics:

  • Real-time, no server storage, direct HTTP GET and POST requests can complete an attack, GET user privacy data.
  • The attacker needs to trick clicks
  • The feedback rate is low, so it is difficult to find and respond to repair
  • Steal sensitive confidential information from users

To prevent non-persistent XSS vulnerabilities, you need to ensure a few things:

  • All content rendered or rendered data for a Web page must come from the server.
  • Try not to start from urls,document.referrer.document.formsWait for this DOM API to get the data directly rendered.
  • Try not to useeval.new Function().document.write().document.writeln().window.setInterval().window.setTimeout().innerHTML.document.creteElement()Methods such as executable string.
  • Failing that, you must also escape the string arguments passed in by methods involving DOM rendering.
  • The front-end rendering will need to do escape encoding for any field.

The purpose of escape is to escape elements that make up an HTML tag, such as
<.
>.
The blank spaceEtc., escape into
<.
>.
 Etc to display escape characters. There are many open source tools available to help us do escape.

A persistent XSS

Persistent XSS vulnerability, also known as storage-type XSS vulnerability, generally exists in Form submission and other interactive functions, such as Posting messages and submitting text information, etc. Hackers take advantage of XSS vulnerability to submit content to the database for persistent storage through normal functions. When the front end page obtains the injection code read out from the database by the back end, Just render it to execution.

The main way to inject pages is similar to the non-persistent XSS vulnerability, except that instead of being persistent from urls, refferers, forms, etc., the persistent is from data that the back end reads from the database. Persistent XSS attacks do not require a decoy click, and the hacker only needs to complete the injection at the place where the form is submitted, but such XSS attacks are relatively expensive. The following conditions must be met for a successful attack:

  • POST request to submit the form without escaping it directly into the library.
  • The back-end retrieves data from the database without escaping it and outputs it directly to the front-end.
  • The front-end takes the back-end data and renders it directly into the DOM without escaping it.

Persistent XSS has the following characteristics:

  • Persistence, embedded in the database
  • The damage is so widespread that it can turn a user’s machine into a victim of DDoS attacks.
  • Steal user sensitive private information

In order to prevent persistent XSS vulnerabilities, the joint efforts of the front and back ends are required:

  • The backend should choose not to trust any front-end data before entering the repository and uniformly escape all fields.
  • The back end uniformly escapes the output data to the front end.
  • The front-end should choose not to trust any back-end data when rendering the PAGE DOM, and any fields should be escaped.

Character set-based XSS

In fact, many browsers and various open source libraries are dedicated to XSS escape processing, trying to default to the majority of XSS attacks, but there are still many ways to bypass the escape rules, it is difficult to guard against. For example, character set based XSS attack is an attack method to bypass these escape processes. For example, some Web pages have unfixed character sets, and users enter characters that are not expected from the character set. Sometimes, escape filtering rules will be bypassed.

Take UTF-7 based XSS as an example. Utf-7 is a character set (now removed from the Unicode specification) that allows all Unicode to be represented as 7 bits. In order to represent all characters with 7 bits, except for numbers and some symbols, the rest of the character set will be base64 encoded.

<script>alert(" XSS ")</script> can be interpreted as: + adw-script + ad4-alert (+ aci-xss +ACI-)+ADw-/script+AD4-Copy the code

Character set based XSS attacks can occur because the browser automatically recognizes the encoding when the meta does not specify a charset, so these attacks usually occur when the meta tag is not specified or has not been specified in time.

So what can we do to avoid this XSS?

  • Remember to specify<meta charset="utf-8">
  • In XML, not only must the character set be utF-8, but the tag must be closed
  • Cow man recommendation: drops.wooyun.org/papers/1327 (speak this pretty detailed)

Cross-site XSS based on Flash

Flash-based cross-site XSS is also a reflection type of XSS, and although there is almost no ActionScript product line today, AS scripts can accept user input and manipulate cookies, An attacker can embed malicious SWF files in a page with other XSS (persistent or non-persistent) methods. Mainly because AS sometimes needs to interact with JS parameters, attackers will tamper with parameters through malicious XSS injection, steal and manipulate cookies.

Ways to avoid:

  • Strictly manage read and write permissions for cookies
  • The parameters that the Flash can accept from the user are filtered to escape

Unauthenticated jump XSS

There are some scenarios where the backend needs to perform a 302 jump on an incoming URL parameter that is ready to jump, possibly with some sensitive cookie information from the user. If the server does a 302 redirect and the redirect address is the user’s input, the attacker can enter a malicious redirect address to execute the script.

In this case, you need to prevent such vulnerabilities in the following ways:

  • Whitelisting or some sort of rule filtering is performed for the parameters of the redirect URL
  • The backend takes care to protect sensitive information, such as cookies using source authentication.

CSRF

Cross-site Request Forgery (CSRF) attack

So what does CSRF do? It’s as simple as this: an attacker can steal your login information and simulate sending requests as you. With the help of a few social engineering tricks, such as links sent through chat software such as QQ (some disguised as short domain names that users can’t distinguish), attackers can force users of Web applications to perform actions that the attackers have preset. For example, when a user logs in to an online bank to check his balance and clicks a link from a QQ friend without logging out, the money in the user’s bank account could be transferred to the account designated by the attacker.

Therefore, CSRF attacks pose serious threats to end users’ data and operation commands. CSRF attacks compromise the entire Web application when the end user under attack has an administrator account.

CSRF principle

The following diagram Outlines how a CSRF attack works. It can be understood that a thief gets the keys to your house from where you made them, and then goes to your house and steals whatever he wants.

Three conditions must be met to complete a CSRF attack:

  1. The user has logged in to site A and logged the cookie locally
  2. Without logging out of site A (that is, when the cookie is in effect), the user visits site B, which is A lure hazard provided by A malicious attacker (site B requires access to site A).
  3. Site A does not do any CSRF defense

You might ask, “IF I don’t meet any of these three criteria, I won’t be attacked by CSRF.” You could say that, but you can’t guarantee that the following won’t happen:

  • You can’t guarantee that once you’re logged in to a site, you won’t be able to open a TAB page and visit another site, especially now that browsers support multiple tabs.
  • You cannot guarantee that your local cookie will expire immediately after you close your browser and that your last session has ended.
  • The alleged attack site B, pictured above, may be a trusted, frequently visited site with other vulnerabilities.

Prevent CSRF

CSRF defense can be performed on both the server and the client. It is better to start CSRF defense from the server. CSRF defense is also performed on the server. There are many ways to prevent CSRF attacks on the server, but the ideas are the same, mainly from the following two aspects:

  • Use GET, POST requests and cookies correctly
  • Add tokens to non-GET requests

Generally speaking, common Web applications are based on GET, POST requests, and cookie requests. We generally design application requests according to the following rules:

  • GET requests are used to view, list, and display resources without changing their properties.
  • POST requests are commonly used to submit From forms, change the properties of a resource, or do something else (database insert, update, delete).

Once GET and POST requests are used correctly, all that remains is to add random numbers to non-GET requests, which can be done in one of three ways:

  • Generate a unique cookie token for each user, and all forms contain the same pseudo-random value. This scheme is the simplest, because the attacker cannot obtain cookies from third parties (in theory), so the data in the form will fail to be constructed. However, the solution must be secure without XSS because users’ cookies can easily be stolen due to XSS vulnerabilities.

  • Each POST request uses a verification code. This scheme is relatively perfect, but it requires users to input the verification code for many times, resulting in poor user experience. Therefore, it is not suitable for extensive application in business.

  • When rendering a form, include a csrfToken for each form, submit the form with a csrfToken, and then do csrfToken validation on the back end.

CSRF defense can be selected based on application scenarios. CSRF defense does require a lot of additional development on top of normal business logic, but the effort is worth it because user privacy and property security are fundamental to the product.

SQL injection

SQL Injection vulnerability is one of the most common security vulnerabilities in Web development. It can be used to obtain sensitive information from the database, or use the characteristics of the database to perform a series of malicious operations such as adding users, exporting files, and even obtain the highest authority of the database and system users.

And because of the cause of SQL injection process is not effective to escape to filter the user’s input, the success of the attacker submit a malicious SQL queries to the server code, the program after receiving the wrong input of the attacker to as part of the query execution, led to the change, the original query logic additional perform the attacker carefully constructed of malicious code.

Many Web developers do not realize that SQL queries can be tampered with, thus treating SQL queries as trusted commands. As it turns out, SQL queries can bypass access control, thereby bypassing authentication and permission checking. Furthermore, it is possible to run host system-level commands through SQL queries.

Principles of SQL Injection

Here are some real life examples to explain how SQL injection works.

Consider the following simple administrator login form:

<form action="/login" method="POST"> <p>Username: <input type="text" name="username" /></p> <p>Password: < input type = "password" name = "password" / > < / p > < p > < input type = "submit" value = "on" / > < / p > < / form >Copy the code

The SQL statement on the back end might look something like this:

let querySQL = ` SELECT * FROM user WHERE username='${username}' AND psw='${password}' `; // Execute the SQL statement...Copy the code

The purpose is to verify that the user name and password are correct. At first glance, there is nothing wrong with the SQL statement above, which can achieve our purpose, but you are only looking at the problem from the point of view of the user will honestly enter as you designed. If a malicious attacker enters the user name zoumiaojiang ‘or 1 = 1 –, enter the password freely, you can directly log in to the system. WFT!

For a moment, the actual SQL statement we envisioned would be:

SELECT * FROM user WHERE username='zoumiaojiang' AND psw='mypassword'Copy the code

Your SQL statement will look like this:

SELECT * FROM user WHERE username='zoumiaojiang' OR 1 = 1 --' AND psw='xxxx'Copy the code

In SQL, — means what follows a comment, so the query statement becomes:

SELECT * FROM user WHERE username='zoumiaojiang' OR 1 = 1Copy the code

This SQL query condition is always true, so it means that malicious attackers can log into my account without my password, and then can do whatever they want in it. However, this is only the simplest injection, the brilliant SQL injection master can even run the host system level command through THE SQL query. I don’t have the ability to go into too much depth here. After all, I don’t specialize in this kind of attack. But through the above examples, we have already understood the principle of SQL injection, and we can basically find a solution to defend against SQL injection.

How do I prevent SQL injection

The main reason for preventing SQL injection is not to allow the user’s input to affect the logic of a normal SQL statement. When the user’s input confidence is going to be used to concatenate an SQL statement, we should always choose not to believe it. Anything must be escaped and filtered. Here are a few considerations for defending against SQL injection:

  • Strictly restrict the operation permissions of the Web application database, and provide the user with the minimum permissions that can only meet the requirements of the user’s work, so as to minimize the harm of injection attacks on the database

  • The back-end code checks that the input data is as expected and strictly restricts the types of variables, such as using regular expressions to do some matching.

  • Special characters (‘, “, \, <, >, &, *,; Etc.) for escape processing, or code conversion. Almost all back-end languages have ways to escape strings, such as the LoDash. _escapeHTMLchar library for LoDash.

  • You are advised to use the parameterized query interface provided by the database for all query statements. Parameterized statements use parameters instead of embedding user input variables into SQL statements. That is, do not directly concatenate SQL statements. For example, in the mysqlJS library’s query method in Node.js? Placeholder parameters.

mysql.query(`SELECT * FROM user WHERE username = ? AND psw = ? `, [username, psw]);Copy the code
  • You are advised to use professional SQL injection detection tools to detect SQL injection vulnerabilities before releasing applications. There are many open source tools such as SQLMap, SQLninja and so on.

  • Avoid website printing SQL error information, such as type error, field mismatch, etc., expose SQL statements in the code, to prevent attackers from using these error information for SQL injection.

  • Don’t be too specific about the error messages returned. If the purpose is to facilitate debugging, use backend logs. Don’t expose too many error messages on the interface.

Encounter to operate the database code, must be careful, careful making ship ten thousand, find a few people for more than a few times more code review, the questions are exposed, and be good at using the tool, the code for handling database related confidential, have no matter to do not go to all kinds of BBS bask in their sites of SQL statements, one thousand have been locked in?

Command line injection

The command line injection vulnerability, where an attacker is able to access a host directly through HTTP requests and execute the attacker’s predefined shell commands, may seem bizarre, but it is often one of the most overlooked and dangerous vulnerabilities for Web developers. Here is an example:

Suppose you need to implement a requirement that the user submits something to the server and then executes some system commands on the server to produce a result back to the user. The partial implementation of the interface is as follows:

Repo const exec = require('mz/child_process').exec; Let params = {/* user input parameter */}; exec(`git clone ${params.repo} /some/path`);Copy the code

This code does meet business requirements, and normal users can download the desired code from the specified Git repo, but like SQL injection, this code is very popular with malicious attackers.

If params repo incoming is https://github.com/zoumiaojiang/zoumiaojiang.github.io.git, of course, no problem. But if params repo incoming is https://github.com/xx/xx.git && rm – rf / * && just your service is to use root’ll be up shit creek.

The details of what a malicious attacker can do with command line injection are as varied as SQL injection, such as “rebound shell injection”, but the principle is the same and we have the absolute ability to prevent command line injection from happening. There are several things you need to do to prevent command-line injection:

  • The back end needs to completely disbelieve the front-end submissions and impose rules on them (such as regular expressions).
  • Command line parameter escape filtering for all incoming parameters before invoking system commands.
  • Do not concatenate command statements directly. Use tools such as Node.js for concatenate and escape preprocessingshell-escapeNPM package.

As in the previous example, we can do the following:

const exec = require('mz/child_process').exec; // use shell-escape NPM const shellescape = require('shell-escape'); Let params = {/* user input parameter */}; If (! /.test(params.repo)) {return; } let cmd = shellescape([ 'git', 'clone', params.repo, '/some/path' ]); / / CMD value: git clone 'https://github.com/xx/xx.git && rm - rf / &&'/some/path / / so as not to be injected into a success. exec(cmd);Copy the code

Regardless of the backend locale, care must be taken when it comes to code calling system shell commands.

DDoS attack

Distributed Denial of Service (DDoS), also known as Distributed Denial of Service (DDoS), is a Distributed Denial of Service that overloads resources with a large number of requests, resulting in the unavailability of services. This attack is not considered a security problem. The act of “injuring a thousand enemies, injuring eight hundred”. In order to protect Web apps from attacks, DDoS attacks are quite common.

DDoS attacks can be understood as: “You open a shop, the next door doesn’t like it, so you hire a bunch of gangsters to sit in your shop and do nothing, and other customers can’t come in, so your business is not good.” Why is DDoS a “self-inflicted attack”? After all, the place next door paid a lot of money to hire gangsters and didn’t get anything for it, did it? The purposes of DDoS attacks are as follows:

  • Hatred, is to kill you
  • Blackmail you, fuck you for nothing
  • Cheat you, if you don’t buy my firewall service, someone will continue to fuck you

Maybe your site has suffered a DDoS attack, but how you interpret it depends. DDos attacks are classified into network layer attacks and application layer attacks, and fast traffic attacks and slow traffic attacks. However, these attacks result in resource overload and service unavailability.

The network layer DDoS

DDos attacks at the network layer include SYN Flood, ACK Flood, UDP Flood, and ICMP Flood attacks.

SYN Flood attack

SYN flood attacks mainly exploit bugs in the TCP three-way handshake. As we all know, the TCP three-way handshake requires the two connected parties to send SYN, SYN + ACK, and ACK packets. When the attacker constructs source IP addresses randomly to send SYN packets, In this case, the server tries to send a SYN + ACK packet again and waits for at least 30 seconds. As a result, the resource saturation service is unavailable. This attack is a slow DDoS attack.

ACK Flood attack

After the TCP connection is established, all the transmitted TCP packets carry THE ACK flag bit. When receiving a packet with the ACK flag bit, the host needs to check whether the connection quad represented by the packet exists. If so, check whether the state represented by the packet is valid, and then pass the packet to the application layer. If the packet is found to be invalid, for example, the port to which the packet is destined is not enabled on the host, the protocol stack of the host operating system responds to the RST packet to inform the peer that the port does not exist.

UDP Flood attack

As UDP is a connectionless protocol, an attacker can forge a large number of source IP addresses to send UDP packets. This type of UDP flood attack is a large-traffic attack. In normal applications, the bidirectional traffic of UDP packets is almost equal. Therefore, the attacker consumes his own resources while consuming the other’s.

The ICMP Flood attack

ICMP Flood attacks are massive traffic attacks. Abnormal ICMP packets are continuously sent. As a result, the target bandwidth is occupied and resources are consumed. Ping is now disabled on many servers (ICMP packets can be blocked on the firewall), so this attack is outdated.

Network layer DDoS defense

DDoS attacks at the network layer are essentially undefendable. What we can do is to constantly optimize the network architecture deployed by the service itself and improve network bandwidth. Of course, do the following things to help mitigate the impact of network layer DDoS attacks:

  • Optimize the network architecture and use load balancing.
  • Make sure that the system files on the server are up to date and that system patches are up to date.
  • Add an anti-ddos device to clean traffic.
  • Limit the number of SYN half-connections that can be opened at the same time and shorten the SYN half-connections Timeout.
  • Limit the frequency of single IP requests.
  • Defense Settings such as firewalls prohibit ICMP packets.
  • Strictly restrict the access to external servers.
  • When running a port mapper or a port scanner, carefully check privileged and non-privileged ports.
  • Shut down unnecessary services.
  • Carefully check the logs of network devices and host/server systems. Any log leak or time change could mean the machine is under attack.
  • Restrict network file sharing outside the firewall. This will give hackers the opportunity to intercept system files, host information exposed to hackers, is undoubtedly to give the other party the opportunity to invade.
  • Add money pile machine..
  • Report to the police.

The application layer DDoS

Application-layer DDoS attacks occur at the application layer, not at the network layer, but after the TCP handshake is established and the application processes the request. Many common DDoS attacks are application-layer attacks. Application-layer attacks vary widely and aim to drain your bandwidth when a network application does. Here are the typical types of attacks in the cluster.

CC attack

In order to defend against DDoS attacks, Green Alliance developed a product called Collapasar, which can effectively defend against SYN Flood attacks. As a provocation, the hackers developed a Challenge Collapasar attack tool (CC).

The principle of CC attacks is to continuously launch abnormal requests for pages that consume large resources, resulting in resource exhaustion. Therefore, before sending CC attacks, we need to look for pages that load slowly and consume more resources, such as pages that need to query databases and read and write hard disk files. Through CC attacks, crawlers are used to make HTTP requests to some pages that consume a lot of resources to load.

DNS Flood

DNS Flood attack methods is to attack the server sends a large number of DNS request, usually request parse domain is randomly generated or network domain name does not exist in the world, be attacked the DNS server will first when receive the DNS request on the server to find whether there is a corresponding cache, If the domain name cannot be found and cannot be resolved by the server, the DNS server recursively queries the domain name information from the upper-layer DNS server. Domain name resolution brings heavy load to the server. If the number of domain name resolution requests exceeds a certain threshold every second, the DNS server times out when resolving domain names.

The maximum number of dynamic domain name queries a DNS server can handle is 9,000 requests per second, according to Microsoft statistics. As we know, tens of thousands of domain name resolution requests per second can be easily constructed on a P3 PC, which is enough to paralyze a DNS server with extremely high hardware configuration, thus showing the vulnerability of DNS server.

HTTP slow connection attack

For HTTP protocol, first establish HTTP connection, set a large conetnt-length, send a few bytes each time, let the server always think that the HTTP header is not completed, so that more connections will soon appear connection exhaustion.

Application-layer DDoS defense

  • Determine user-Agent fields (unreliable because they can be constructed arbitrarily)
  • Limit the frequency of access for IP + cookies (since cookies can be changed, IP can use proxies, or broilers, which are also unreliable)
  • Disable the maximum number of server connections and properly configure the middleware to mitigate DDoS attacks.
  • Add a captcha to the request, such as when there is a database operation in the request.
  • When writing the code, optimize as far as possible, and make reasonable use of caching technology, reduce the database read operation.
  • Add money pile machine..
  • Report to the police.

Defense at the application layer is sometimes more difficult than that at the network layer, because there are many factors that can lead to DDoS attacks on the application layer. Sometimes, it is because of programmer errors that a page takes a lot of resources to load, sometimes because of improper middleware configuration, and so on. The core of application layer DDoS defense is the distinction between human and machine (crawler), because a large number of requests cannot be human, must be constructed by machine. Therefore, if we can distinguish human and reptilian behaviors effectively, we can defend against this attack well.

Other DDoS Attacks

It takes a lot of bandwidth to launch a DDoS attack, but the Internet is like a forest of birds, and DDoS attackers can find other ways to launch cheap and deadly DDoS attacks.

Using the XSS

For example, if 12306 page has an XSS persistent vulnerability discovered by malicious attackers, just in the Spring Festival ticket rush period in this vulnerability to execute the script to a small site randomly send some requests, and then with the increase of user access, the increase of infected users, the attacked site will naturally be quickly paralyzed. This kind of DDoS is simply a no-cost, no surprise, there are not too many XSS vulnerabilities in big sites now.

From P2P network attacks

As we all know, P2P users and traffic on the Internet are a huge number. If they all go to one designated place to download data, thousands of real IP addresses are connected, and no device can hold up. Taking Bittorrent for example, forgery some popular video seeds and Posting them to search engines is enough to fool many users and traffic, but this is only a basic attack. Advanced P2P attacks directly trick resource management servers. For example, the Thunderbolt client will upload their discovered resources to the resource management server, and then push to other users who need to download the same resources, so that a link is published. Through protocol reverse, an attacker forges a large number of popular resource information and distributes it through the resource management center. The information can be spread throughout the P2P network instantly. To make matters worse, the attacks cannot be stopped, not even by the attackers themselves, until P2P officials discover the problem and update the server, and users restart the download.

Finally, it is impossible to prevent DDoS, just like your shop can only accommodate 50 people, the triad has 100 people, you can change a big shop, can accommodate 500 people, and then the triad finds another 1000 people, this kind of head pile is the essence of DDoS attack and defense, “a foot higher, the devil is ten feet higher, The devil is one foot high, the road is one foot high “, to tell the truth, when necessary to agree to blackmail your person’s conditions, really not on the police.

Traffic was hijacked

Traffic hijacking is a mainstay of the black industry, isn’t it? It is disgusting to vomit, do not ridicule, or continue to talk about dry goods, traffic hijacking is basically divided into two kinds: DNS hijacking and HTTP hijacking, the purpose is the same, when the user visits Zoumiaojiang.com, it is not or not exactly the “content” provided by Zoumiaojiang.com.

DNS hijacking

DNS hijacking, also called domain name hijacking, so to understand, “you hit a car wants to go to the store to have a meal, the results of your car is playing small workshops, sent directly to you to mix”, the function of DNS is the network address of the domain name corresponding to the IP address of the real computers able to identify, so that the computer can further communication, Deliver web addresses, content, etc. If a tampered DNS server returns the IP address of a malicious phishing site when a user accesses a site using a domain name, the user will be hijacked to the phishing site, and then the user will be phished by entering various account and password information to leak privacy.

This kind of hijacking, or is the ghost of network operators, generally small network operators and black collusion will hijack DNS, or computer poisoning, was maliciously tampered with the router DNS configuration, basically as a developer or webmaster is difficult to detect, unless there is user feedback, Now the upgraded version of DNS hijacking can also be specific users, specific areas, such as the use of user portrait screening user hijacking method, in addition, this kind of advertising display is more random and smaller, the general webmaster unless users complain otherwise it is difficult to detect, even if the discovery of evidence is more difficult to report. However, if you receive feedback about DNS hijacking, do the following:

  • Forensics is very important, time, location, IP, dial-up account, screen shots, URL address, etc.
  • You can complain to the telecom operators in the hijacking area.
  • If the complaint feedback is not effective, directly to the Ministry of Industry and Information Technology complaints, generally will add white your domain name.

HTTP hijacked

HTTP hijack so you can understand, “you hit a car wants to go to the store to have a meal, the driver with you all the way to let you pass small workshops of advertising”, HTTP hijacked mainly when users visit a site through a carrier networks, the illegal operators and black collusion can intercept HTTP request returns content production, and be able to tamper with the contents, And then return to the user, so as to realize the hijacking of the page, light insertion of small advertising, heavy directly tampered into a phishing site page to cheat users privacy. The fundamental reason for traffic hijacking is that HTTP cannot verify the identity and data integrity of the communicating party. If this problem can be solved, traffic hijacking will not happen easily. So the only way to prevent HTTP hijacking is to encrypt the content so that the hostage-taker can’t crack the tampering, thus preventing HTTP hijacking.

HTTPS is a secure and encrypted network application layer protocol based on SSL, which can prevent HTTP hijacking. There’s a good article here. I’m not going to go into HTTPS here, but I’ll talk a little bit more about HTTPS when I get a chance. If you don’t want your site to be HTTP hijacked, make your entire site HTTPS.

Server vulnerability

In addition to the well-known vulnerabilities and notorious attacks mentioned above, there are many other vulnerabilities that are easily overlooked, and a few of them are discussed in this section.

Unauthorized operation loopholes

If your system has login controls, you need to be very careful, because it is very likely that your system has an unauthorized operation vulnerability, which can be summarized as “user A can see or manipulate user B’s private content”, especially if your system has permission controls. So every request needs to make a userID judgment

Here’s a snippet of buggy back-end code:

// let msgId = ctx.params.msgid; // let msgId = ctx.params.msgid; mysql.query( 'SELECT * FROM msg_table WHERE msg_id = ? ', [msgId] );Copy the code

Msg_id = msg_id = msg_id = msg_id = msg_id = msg_id = msg_id = msg_id = msg_id

// let msgId = ctx.params.msgid; // let msgId = ctx.params.msgid; let userId = ctx.session.userId; Mysql. query('SELECT * FROM msg_table WHERE msg_id =? AND user_id = ? ', [msgId, userId] );Copy the code

With more stringent permissions, every operation involving the database would need to be validated first, and account and permission associations for userIDS would need to be considered when designing the database tables.

Directory traversal vulnerability

A directory traversal vulnerability is a vulnerability that can be exploited by constructing… /,./ and similar cross-parent directory string ASCII encoding, Unicode encoding, etc., complete directory jump, read the operating system under each directory sensitive files, can also be called “arbitrary file reading vulnerability”.

Directory traversal vulnerability principle: the program does not adequately filter user input.. /, which allows the user to submit a directory jump to traverse any file on the server. Use multiple.. Symbol, jumps up and down, eventually stopping at root /, to read any file through the absolute path.

Directory traversal vulnerability several examples and tests, the general structure of THE URL and then use the browser directly access, or use the Web vulnerability scanning tool detection, of course, can also write a program to test.

http://somehost.com/.. /.. /.. /.. /.. /.. /.. /.. /.. /etc/passwd http://somehost.com/some/path?file=.. /.. / Windows/system. Ini # with % 00 null character truncation is a more classic attack technique, http://somehost.com/some/path?file=.. /.. / Windows/system. Ini % 00. The js # using the IIS script directory to mobile directory and execute instructions at http://somehost.com/scripts/.. %5c.. /Windows/System32/cmd.exe? /c+dir+c:\Copy the code

The defense is that the URL or parameter needs to be.. /,./ and other characters to escape.

Physical path leakage

Physical path leakage is a low-risk defect, and its harm is generally described as “attackers can use this vulnerability to obtain information to further attack the system”. Usually, the vulnerability is caused by the error information of the system reporting error 500 directly returned to the page. Getting the physical path sometimes gives attackers useful information. For example, you can get a rough idea of the file directory structure of the system. You can see the third-party software used by the system; You might even get a legitimate username (since many people use their username as a directory name for a website).

The way to prevent this kind of leakage is to do a good job of the backend program error handling, custom special 500 error page.

Source code exposure vulnerability

Similar to physical path leaks, an attacker can request access to the back-end source code of your site and then further investigate the attack on the system. So what causes the source code to be exposed? The koA server can specify the directory of static resources through the KOA-static middleware so that static resources can be accessed through the route of the path. For example, your system source directory looks like this:

|- project
    |- src
    |- static
    |- ...
|- server.jsCopy the code

If you want to configure the static folder as a static resource directory, you should do the following in server.js:

const Koa = require('koa');
const serve = require('koa-static');
const app = new Koa();
app.use(serve(__dirname + '/project/static'));Copy the code

But if you misconfigure the directory of static resources, you can cause serious problems, such as:

// ...
app.use(serve(__dirname + '/project'));Copy the code

In this way, all source code can be accessed through routing. All servers provide static resource mechanism, so when configuring static resource directory and path through the server, it must be checked, otherwise it is likely to generate vulnerabilities.

Finally, hope that Web developers can manage their own code of privacy, pay attention to the code security issues, such as not to put the product code containing sensitive information in the third party external site or exposed to external users, especially the front-end code, similar to the private key of confidentiality don’t output directly in the code or page. There may be more to note, but at the end of the day, you have to be careful with every line of code.

Shout… I am so tired that I have been writing intermittently for several days. If there are omissions or deficiencies, I will continue to supplement them

This article is an original article, and it will often update knowledge points and correct some mistakes. Therefore, please keep the original source for reprinting to facilitate traceability, avoid the misleading of old wrong knowledge and have a better reading experience.


Please indicate the source of reprint:
Zoumiaojiang.com/article/com…