This blog is about server side security application security, learning content from white Hat on Web security.

Continuing from the last article on client security, it includes injection attack, authentication and session management and access control, access control, encryption algorithm and random number, Web framework security, application layer denial of service attack DDOS, Web Server security and other aspects.

@

directory

  • Injection attacks

    • SQL injection

      • The blinds
      • Timing Attack
    • Database attack Techniques

      • Common attack cunning
      • Command execution
      • Attacking stored procedures
      • Coding problem
      • SQL Column Truncation
    • Defend against SQL injection properly

    • Other Injection attacks

  • File upload vulnerability

    • File upload Vulnerability Overview
    • Feature or Bug
    • Design a secure file upload function
  • Authentication and session management

  • Access control

  • Encryption algorithm and random number

    • An overview of the
    • Stream Cipher Attack
    • WEP cracking
    • Flaws in the ECB model
    • Padding Oracle Attack
    • Key management
    • Pseudo random number problem
  • Web Framework Security

  • Application layer Denial-of-service attack DDOS

    • The application layer DDOS
    • Verification code
    • Defends against DDOS at the application layer
    • Resource depletion attack
    • A problem caused by ReDOS re
  • PHP security

  • Web Server security

  • Internet companies operate safely

Injection attacks

Because the application violates the “data and code separation principle”. Two conditions: 1. The user can control the input of data; 2. The code cobbles together the data entered by the user.

SQL injection

The blinds

The injection attack is completed when there is no error echo from the server. Validation method: Construct a simple conditional statement to determine whether the SQL statement is executed based on whether the page has changed.

Timing Attack

Using some special functions in the database, you can conditionally cause delays.

For example, in MySQL, using the BENCHMARK() function, you can run the same function several times, so that the return result takes longer than the average time. By changing the time, you can determine whether the injected statement is successfully executed. This is a side-channel attack.

Eg:

1170 UNION SELECT IF(SUBSTRING(current.1.1) =
CHAR(119),BENCHMARK(5000000.ENCODE('MSG'.'by
5 seconds')),null) FROM (Select Database(a)as current) as tbl;
Copy the code

The Payload determines whether the first letter of the library name is a CHAR(119), which is a lowercase w. If the result is true, a long delay is caused by the BENCHMARK() function. If not true, the statement completes quickly. The attacker iterates through all letters until the entire database name has been validated.

In addition, a lot of information about the database can be obtained by means such as this.

Database attack Techniques

Common attack cunning

SQL injection can guess the version of the database. There e is an automated tool to guess username and password. Guess the answer. Violence), can get the current user’s identity, to perform further file operations, LOAD_FILE read, then INTODUMOFILE write system, and finally LOAD DATA INFILE into the file into the table. This technique can be used to export the Web-shell for further attacks.

Automatic injection tool: SQLMap

Command execution

In MySQL, you can use user-defined Functions (UDFs) to execute commands in addition to exporting Web shell commands directly. If the current user is root, the user can directly obtain the root permission.

Attacking stored procedures

Stored procedures provide powerful functionality for databases, but must be executed using CALL or EXECUTE. In the process of injection, storage after the attacker provides great convenience. For example, in MS SQL Server, run xp_cmd-shell to run system commands.

Coding problem

Special characters such as single and double quotation marks commonly used in injection attacks. When a data set is “wide character set”, some vulnerabilities arise, such as several encodings representing one character, for example.

0xbf27 or 1=1 becomes 0xbf5C27 (the ASCII code for “\” is 0x5c) after being escaped, but 0xbf5c is a character. So the original escape character \ will “eat”.

A good way to do this is to set the charset attribute of the meta tag on the page to UTF-8.

SQL Column Truncation

In the MySQL database, if the strict mode is not enabled, duplicate data insertion or other illegal data insertion may occur, and unauthorized access may be obtained.

Defend against SQL injection properly

  • Find all SQL injection vulnerabilities

  • Fixing these holes

    Use precompiled statements: The best approach is to use precompiled statements that bind variables so that user input cannot change the structure or semantics of the statement.

    Use stored procedures: Define SQL statements in the database instead of using dynamic SQL statements.

    Check data types and use safety functions

    From a database perspective, the principle of minimum permissions should be used.

Other Injection attacks

  • XML injection: Similar to HTML injection
  • Code injection: Execute commands indirectly through functions that execute commands, such as eval(), system()
  • CRLF injection: The two characters \n \t denote a newline, which is injected to change the semantics. Eg: Rewriting log files and injecting HTTP headers (HTTP Response Splitting), because HTTP headers are \n\ T newlines, may cause security risks and can form XSS attacks.

File upload vulnerability

File upload Vulnerability Overview

File upload vulnerability refers to a vulnerability in which a user uploads an executable script file and obtains the ability to execute server-side commands through the script file.

Common Security Vulnerabilities

  • Uploading files is a Web scripting language

  • Upload files are Flash’s policy robust crossdo-main.xml, and hackers can control Flash’s behavior below this domain

  • Upload files are viruses, Trojan files that induce users or administrators to download execution

  • Upload files are phishing images or images that contain scripts for phishing and fraud

    Conditions: 1. The uploaded file can be interpreted and executed by the Web container. 2. Users can access the file from the Web. 3. The uploaded files are not checked or formatted

    Eg: Open source rich text editor file upload function.

    Bypass file upload check function:

    1. An attacker manually modifies the POST packet in the upload process and adds %00 characters to truncate the judgment of file names by certain functions.

    2. Forge a valid file header and place the real script file behind it.

Feature or Bug

  • Apache file parsing problem: Apache on the file name resolution from the back to the front, until Apache recognize the file type. Defined in the mime.types file of Apache.
  • IIS file parsing problem: 1. Become truncated characters, such as evil.asp; Xx.jpg, IIS 6 will parse this file to evil.asp for execution. 2. Handle folder extension error, files in /*. Asp/folder are treated as asp
  • PHP CGI path parsing problem: PHP in Nginx as a Web Server, generally use fastCGI as the script interpreter, and fastCGI mode, PHP to obtain environment variables, if the resolution cannot be resolved, the path will be a step forward to seek environment parsing.
  • Phishing using upload file vulnerability: Jump from a normal domain name to a phishing site, parse different file types, and still appear to be a trusted domain name on the domain name, but the HTML file runs through *.html.jpg parsing.

Design a secure file upload function

  • The directory for uploading files is set to unexecutable
  • Determine the file type and use a whitelist policy, not a blacklist policy
  • Rewrite file names and file paths using random numbers
  • The domain name of the file server is set separately

Authentication and session management

  • The concepts of “authentication” and “authorization”, single-factor authentication and multi-factor authentication
  • Password: the most basic authentication method. OWASP has recommended best practices.

OWASP: The Open Web Application Security Project (OWASP), an online community, produces freely-available articles, methodologies, documentation, tools, and technologies in the field of web application security.

Using weak passwords is much more effective than brute force cracking. Do not save the password in plain text. Use irreversible encryption algorithm or single hash function algorithm.

  • Multi-factor authentication: Raise the attack threshold

  • Session and authentication: The Session ID is encrypted and stored in a Cookie, which is protected by the same Origin policy of the browser. Session hijacking means that the Session ID is stolen during the lifetime, which is equivalent to account theft. If the Session ID is stored in a Cookie, it is called cookiejacking.

    • Session leakage can be traced through XSS attacks, network sniffing, and local Trojan horse theft.
  • Session Fixation attack: A problem that can cause Session Fixation if the user’s Session ID does not change during login to a website.

    • The specific attack process is that user X (attacker) obtains an unauthenticated SessionID and then gives the SessionID to user Y for authentication. After the authentication is completed, the server does not update the value of the SessionID (note that the SessionID is not changed). So X can directly log into Y’s account with this SessionID.
  • Session persistence attack: After a user is inactive for a long time or clicks exit, the server destroys the Session. If the Session remains valid, the Session hijacking attack results.

    Some websites have a large number of visits, so the server does not maintain the Session, encrypts and saves the Session in the Cookie, and controls the expiration time of the Session with the Cookie Expire tag. This can hijack sessions by XSS attacking the client’s Cookie expiration time.

    • Periodic forced Cookie destruction, a user can have several sessions at the same time
  • SSO single sign-on: A user can log in to all systems once. It concentrated the risk. The most commonly used is OpenID, which authenticates users using urls and redirects them back to the site after successful authentication.

Access control

  • What Can I Do?

    Authorization issues: permission control, access control. A certain subject to an object need to implement a certain operation, and the system of this operation is the limit of authority control. The network request was restricted by the firewall ACL policy. Procedure The addition of page-based access control can solve the problem of unauthorized page access.

  • Vertical Rights Management

    Role-based Access Control (RBAC) : role-based Access Control. The minimum permission rule is adopted.

  • Horizontal rights Management

    Data of the same user cannot be accessed directly, that is, the problem is caused by the same role, which is still a problem today.

    Eg: The laiyi shopping website does not control the user's permission. You can view the individual with the corresponding ID by changing the ID parameter in the URLCopy the code

    Private information such as name and address.

  • Introduction of request

    A security protocol that authorizes third-party applications to access Web resources without providing a user name or password. OpenID takes care of authentication, OAuth takes care of authorization.

    There are three characters:Copy the code
  • User: User

  • Resource Owner: the Resource provider whose data is required for users to access other web applications

  • Client: a web application that a user is accessing

Process steps are not described and understood.

Encryption algorithm and random number

An overview of the

Encryption algorithm is divided into packet encryption algorithm and stream password encryption algorithm.

Block encryption: DES, 3-DES, Blowfish, IDEA, AES, etc.

Stream password encryption algorithms: RC4, ORYX, and SEAL.

Based on the information available to the attacker, the attack can be classified into ciphertext only attack, known plaintext attack, selected plaintext attack, and selected ciphertext attack.

Stream Cipher Attack

Stream ciphers a common encryption algorithm that operates on one byte at a time, based on xOR operations, but performs very well.

  • Reused Key Attack: To use the same Key in flue to encrypt several times, because it is based on XOR operation, so knowing only four data in flue can be used to infer the remaining one.

    E(A) = A xor C

    E(B) = B xor C

    E(A) xor E(B) = A xor B;

  • ; bit-flipping Attack: In cryptography, an Attack in which the attacker changes the ciphertext, without knowing it, so that the text changes as desired. That is, if you know the plaintext of A and B and the ciphertext of A, you can deduce the ciphertext of B.

    Resolve bit-flipping attacks, and verify the integrity of ciphertext.

  • Weak random IV problem: AuthCode () uses 4-byte IV (keyc in the function) by default, which makes it harder to crack. But in fact, 4-byte IVs are very fragile, it’s not random enough, we can find duplicate IVs by brute force.

WEP cracking

WEP is a wireless encryption transmission protocol. If you break the key of WEP, you can connect to Access Point.

Two key factors:

  • B) Initialization vector IV: clear text sent, in short time will be repeated, can be used in Port Key Attack. At the same time, if you find the same IV, you can construct the same CRC-32 check, and make a successful bit-flipping.
  • Crc-32 validation of messages

Security of the WEP algorithm proposed the theory of WEP cracking.

Flaws in the ECB model

Group independent encryption, the exchange of any group of ciphertext, so decrypted after the plaintext is also switched position. So you should use chain encryption.

Padding Oracle Attack

During block encryption, padding is used to fill in less than digits. The key to a Padding Oracle Attack is that the attacker knows whether the decrypted result matches the Padding. Keep this in mind when implementing and using CBC mode block encryption algorithms.

Key management

Cryptography is a principle that the security of a cryptosystem should depend on the complexity of the key, not on the secrecy of the algorithm.

Prevent the key from being leaked in an abnormal way. Do not hardcode private keys into code, use public/private key management or improve key management. Centralized key management reduces the coupling between the system and the key and facilitates periodic key replacement.

Pseudo random number problem

Pseudo random numbers are not random enough.

  • Timestamps are not random enough to be used directly for random number generation.
  • Mt_rand () = mt_rand();
  • Use safety random algorithm, in JAVA using JAVA. Security. SecureRandom, etc.

Web Framework Security

  • MVC Framework security

    MVC framework in modern development. From the direction of data inflow, the data has passed through the View layer, Controller layer and Model layer. When designing a security scheme, the key factor of data should be grasped. Solve related problems at each level, don’t leave problems that don’t belong at that level to that level.

Template engine and XSS defense

Solve XSS problems in the View layer. The page is rendered in the View layer using a template engine, which may provide some encoding methods

Eg: Django uses htmlEncode() to keep auto-escape safe, but sometimes turning it off can cause problems.

  • Web Framework and CSRF defense

    You can use security tokens to overcome CSRF attacks. Separate read and write operations and submit all “write operations” through POST. At the same time, ensure the privacy of security tokens and automatically add tokens to POST.

    1. Bind tokens in the Session. 2. Automatically add the Token field in the form form. 3. Automatically add tokens to Ajax requests. 4. On the server, check whether the tokens submitted in POST are the same as those bound in Session.Copy the code
  • Management of the HTTP Headers

    In the framework, HTTP headers are globalized. Eg: CSRF attack on HTTP headers. Jumps to HTTP Response returned by 30X – provides a unified jump function (whitelist).

  • Data persistence layer and SQL injection

    Using the ORM framework has the advantage of preventing SQL injection.

Application layer Denial-of-service attack DDOS

DDOS: Distributed denial of service (DDOS), which amplifies normal services by several times. Attacks are launched simultaneously from several network nodes to achieve scale effect.

Common DDOS attacks include SYN flood, UDP flood, and ICMP flood.

In many anti-ddos products, a variety of algorithms are generally used, combined with some characteristics of DDOS attacks, convectionCopy the code

Amount of cleaning. Anti-ddos network devices can be connected in series or parallel at the network egress.

The application layer DDOS

The TCP three-way handshake is complete at the application layer, the connection is established, and the attack IP address is real. This attack is an attack on server performance that can be mitigated by optimizing server performance.

  • CC attack: Continuously launches normal requests to the application pages that consume large resources to consume server resources.
  • Limit the frequency of requests: Limit the frequency of requests per client.

Verification code

CAPTCHA: Automatic Turing Test to Distinguish computers from humans.

Possible vulnerabilities: 1. Directly use image correlation algorithm to identify the verification code. 2. Generate all captcha images in advance and use the hashed string as the file name of the captcha image – use enumeration to crack.

Defends against DDOS at the application layer

The core of captcha is to identify people and machines. In general, the client is identified by the User-Agent field in the HTTP header.

A more reliable alternative is to have the client parse a piece of JS and give the correct results, since most of the automation is done directly by constructing HTTP packages, not in the browser environment.

Web Server can also be used for defense.

Resource depletion attack

  • Slow Loris attack: An attacker sends HTTP requests to the Web Server at a very low speed. As the number of concurrent connections to the Web Server is limited, all connections are occupied maliciously.
  • HTTP POST DOS: When sending HTTP POST packets, specify a very large Content-Length value and send the packets at a very low speed, such as 10-100s sending a byte, to keep the connection open.
  • Server Limit DOS: Cookies cause a denial of service. The Web Server has a length limit on HTTP headers. If an attacker maliciously writes a super-long Cookie to the client through XSS attacks, the client cannot access any pages in the domain where the Cookie is located before clearing the Cookie.

A problem caused by ReDOS re

When a regular expression is poorly written, it can be exploited by malicious input and consume a lot of resources, resulting in DOS. This attack is called re-DOS. This is a bug in a code bug.

Eg: ^(a+)+$. Normally, when entering AAAax, there are 16 possible paths, but when entering aaAAAAAAAAAAAAAAAax, there are 65536 paths, which greatly increases the speed of regular engine parsing. When users maliciously construct input, the efficiency of defective regular expression is greatly reduced.

PHP security

Skip this chapter for the moment and come back to it when you write about POC in detail.

Web Server security

  • Apache security: 1. The Apache Module is most prone to security vulnerabilities, so check the installation of the Module

    1. To specify that the Apache process runs as a separate user, you usually need to create a separate user/group for Apache. Running as root is a very bad habit.
    2. Apache has some configuration parameters to optimize server performance and improve the ability to resist DDOS attacks.
    3. Protect the Apache log. After an attacker successfully intruders, the Apache log will be modified and cleared.
  • Nginx security: Pay attention to the security of the software itself and configure parameters.

  • JBoss remote command execution: JMX-Console management background, provides many powerful functions to the administrator, but also convenient for hackers to invade. Load the WAR package remotely.

  • Tomcat remote command execution: The Tomcat Manager background is prone to vulnerabilities.

Internet companies operate safely

Here is the main understanding of Internet company security, here excerpt some important views, do not discuss in detail.

  • Security is a feature of the product.

  • Good safety plan

    • Good user experience
    • Excellent performance