Web Security Development Specification Manual V1.0
1、 Background
The team has recently been frequently subjected to network attacks, which has attracted the attention of the technical leader. The author has a relatively better understanding of security in the team, so I spent some time editing a security development self check list. I think there should also be many readers who need it, so I shared it.
2、 Encoding Security
2.1 Input Validation
Explanation of inspection items
Overview: Any data submitted from the client, such as URLs and parameters, HTTP headers, Javascript, or other embedded code, is considered untrusted data. Each component or functional boundary within or outside the application is verified as a potential malicious input
If untrusted data on the whitelist can be set for whitelist verification, all data that matches the whitelist should be accepted and other data should be blocked
When untrustworthy data on the blacklist contains bad input characters, such as empty bytes (% 00), line breaks (% 0d,% 0a, r, n), path characters (../or..), it is recommended to directly block the data. If the data needs to be accepted, different methods of purification should be performed
Normalize the purification and validation of untrusted data, such as converting relative paths such as directory traversal (./or) into absolute path URL decoding.
When various purification processes are required to purify untrusted data, malicious characters should be completely removed, leaving only known and safe characters, or they should be appropriately encoded or "escaped" before processing. For example, HTML encoding of data when outputting to application pages can prevent script attacks
Legitimacy verification of untrusted data includes: data types such as characters, numbers, dates, and other characteristics; Data Scope; Data length, etc
Before preventing SQL injection of untrusted data into backend database operations, it is recommended to use parameterized queries with positive angles to avoid SQL injection
When the untrusted data in the file verification is a decompressed file, if the file is located outside the service directory or the file size exceeds the limit, it should be rejected for processing
After the untrusted data in access control passes the above verification, it should also be confirmed whether the submitted content matches the user's identity to avoid unauthorized access
2.2 Output Verification
Explanation of inspection items
Overview: Considering the security of the target compiler, correctly encoding all output characters
When untrustworthy data is output to the front and back pages in the encoding scenario, relevant encoding is performed based on the output scenario, such as HTML entity encoding and UR encoding
The purification scenario focuses on operating system commands, SQL, and LDAP queries, purifying all sensitive information output, such as bank cards, phone numbers, system information, etc
2.3 SQL injection
Explanation of inspection items
Overview: Verify the validity of user input before entering the SQL operation of the application.
Parameterized processing uses parameterized queries (PDO for PHP, PreparedStatement for Java, and Sqlparameter for C #) to escape sensitive characters such as' 'and then perform SQL operations.
Minimize authorization: Configure minimum database operation permissions for each application, prohibit database operations with administrator permissions, and limit the number of operation connections.
Sensitive data encryption uses encryption, hashing, or obfuscation methods to store sensitive information confidentially, reducing the risk of data leakage caused by potential vulnerabilities
Prohibit error echo. Prohibit the system from returning prompts containing sensitive information when turning on Debug mode or exceptions. It is recommended to use a custom error information template. Exception information should be stored in the log for security auditing
2.4 XSS Cross Station
Explanation of inspection items
Input validation filters and escapes input data, including but not limited to dangerous special characters such as<>"9% 0&+V"
Output encoding, input data output to different scenarios for different forms of encoding. If output to HTML tags, perform HTML encoding. If output to URLs, perform URL encoding. If output to JS, perform Script encoding. If output to Stylet, perform CSS encoding
2.5 XML injection
Explanation of inspection items
Input validation filters parameters submitted by users, such as special characters such as<,>&, when referencing data internally or externally in XML documents. Prohibit loading external entities and error reporting
Suggest output encoding to escape XML element attributes or content
2.6 CSRF Cross Site Request Forgery
Explanation of inspection items
Use Token to add the Token field generated by the session to the form for important operations. After submission, verify the field on the server
Secondary verification requires users to perform secondary identity verification such as password, image verification code, SMS verification code, etc. when submitting key forms
Referer validation verifies whether the Referer: field in the user request has cross domain submissions
3、 Logical security
3.1 Identity verification
Explanation of inspection items
Overview: All access to non-public web pages and resources must follow a standard and universal authentication process on backend services
The user's credentials must be encrypted and submitted through POST when submitting credentials. It is recommended to use the HTPS protocol to encrypt the channel and authenticate the server
Safely handle failed identity verification with error prompts, such as using "username or password error" to indicate failure and prevent excessive information leakage
The exception handling login entrance should have measures to prevent brute force or database collision guessing (using the leaked password dictionary for batch login attempts). If more than one verification failure occurs, Turing testing will be automatically enabled. If more than one verification failure occurs, account locking mechanism will be automatically enabled to restrict access
When performing key operations such as account password modification, data update, transaction payment, etc., the second verification starts with the Turing test, and then performs the second verification of the user's identity. The transaction payment process should also form a complete evidence chain, and the transaction data should be digitally signed by the initiator
For highly sensitive or core business systems with multi factor authentication, it is recommended to use multi factor authentication mechanisms such as SMS verification codes, software and hardware tokens, etc.
3.2 SMS verification
Explanation of inspection items
The complexity of generating a verification code should be at least 6 digits or letters, and it should be used once. It is recommended that the validity period should not exceed 180 seconds.
The verification code limit is set to once every 60 seconds for users at the front and back ends. It is recommended that each user obtain up to 10 SMS messages per day
Add safety tips: At least include information such as the function of this operation, the verification code sending number, and whether it is an individual's own risk of operation.
Voucher verification prohibits the return of verification codes in the response. The server simultaneously verifies credential information such as passwords and SMS verification codes to prevent vulnerabilities in multi-stage authentication bypass.
3.3 Turing test
Explanation of inspection items
The complexity of generating verification codes should be at least 4 digits or letters, or verification methods such as puzzles should be used once, with a recommended validity period of no more than 180 seconds
Suggestion for using verification codes from the perspective of user experience and security, which can be designed to automatically pop up the verification code input box for verification when the user enters the wrong password once
Verification code verification is prohibited from returning verification codes in the response. Verification code verification should be performed on the server side
3.4 Password Management
Explanation of inspection items
When setting a password, it should meet the requirements of 8 or more digits in length, including uppercase and lowercase letters, numbers, and special characters. User password settings must undergo backend verification, and it is not allowed to set sensitive passwords that do not meet the complexity requirements.
When storing user passwords, a hash algorithm (such as SHA1) should be used to calculate the summary values of user passwords and unique random salt values (Salt) to store their summary and Sat values. It is recommended to store these two values separately
Password modification: When a user changes their password, the modification operation requires authentication through both their phone number and email address. When changing the password, the user should be notified via text message or email if the operation was done by themselves, informing them of the security risks
When retrieving a user's password, the backend needs to perform a secondary verification of the registered phone number or email. The verification code and verification link should be sent to the pre registered address, and the validity period should be set to prevent brute force cracking. Security questions should support as many random questions as possible. In multiple verification operations, it is necessary to sort each verification mechanism to prevent security risks such as skipping the previous verification mechanism and proceeding directly to the final step of authentication
Password usage: In application development, it is prohibited to set universal passwords, hardcoded plaintext passwords, operate using database administrator accounts, operate using different user public accounts, or output passwords to log files or consoles
3.5 Session Security
Explanation of inspection items
To prevent session hijacking during application authentication, it is recommended to continue using HTTPS connections and use the HTTPS protocol for authentication sites. If the connection is redirected from preventing session hijacking HTTP to HTTPS, the session identifier needs to be regenerated. Prohibit back and forth conversion between HTTP and HTTPS, which may lead to session hijacking
When setting session identifier security settings for session cookies, correctly set the 'Httpoly' attribute (prohibiting programs from adding 5 scripts to read cookie information) 'Secure' attribute (prohibiting cookie security settings and preventing cookies from being transmitted to the server through HTTP connections for verification); The "Domain" attribute (the authorized access domain name that can be specified during cross domain access) and the "Path" attribute (the directory path that can be accessed by authorization).
Cookie security settings should place the session identifier in the header information security of the HTP or HTPS protocol, prohibiting transmission with GET parameters and recording the session identifier in error messages and logs
A complete session management mechanism has been implemented on the server side to prevent CSRF attacks, ensuring that every CSRF session request is protected from legitimate authentication and permission control, and preventing cross site request forgery (CSRF) vulnerabilities from occurring.
The session validity period should be set based on balancing risk and functional requirements. Regularly generating a new session identifier and invalidating the previous session validity identifier can alleviate the risk of session hijacking caused by the theft of the original active identifier.
The session logout and logout function is applied to all authenticated web pages. After logging out of a user's session, they should immediately clear the session related information and terminate the relevant session connection
3.6 Access Control
Explanation of inspection items
The control method separates the logical code of access control from other code in the application, and the server manages access control based on session identification.
Control management restrictions: Only authorized users can access protected URLs, files, services, application data, configurations, direct object references, etc
Interface management restrictions allow only authorized external applications or interfaces to access protected local programs or resources
Permission change When permission changes occur, a log should be recorded and the user should be notified whether the operation was done by themselves, informing them of the existing security risks
3.7 File Upload Security
Explanation of inspection items
When uploading files for identity verification, verify the legitimacy of the user's identity on the server
When uploading files, legitimacy verification is performed on the server to verify the file attributes. The whitelist format checks the document type (such as the file's trailing name, file header information verification, etc.) and size (image verification length, width, and pixels, etc.).
When saving files in storage environment settings, they should be saved in a document server that is independent of the application environment (configured with an independent domain name), and the saved directory permissions should be set to non executable
When hiding the file path for file saving, the successfully uploaded file needs to be randomized and renamed, and it is prohibited to return saved path information to the client.
When downloading files through file access settings, they should be downloaded in binary format. It is recommended not to provide direct access (to prevent Trojan files from being executed directly)
3.8 Interface Security
Explanation of inspection items
Network restrictions on the caller's network, such as verification through technical measures such as firewalls, host hosts, and Nginx deny.
Identity authentication is used to verify the identity of the caller, such as key, secret, certificate, and other technical measures. It is prohibited to share credentials
Data security for integrity verification calls, using SHA1 and other digest operations for digital signature of all parameters to identify data tampering
The parameter check for legitimacy verification calls, such as whether the parameters are complete, whether the timestamp and token are valid, and whether the calling permission is legal
Availability requirements: Service requirements for calling, ensuring data consistency by ensuring equal power of calls, and limiting call frequency and validity period
Exception handling of calls, real-time detection of call behavior, and timely blocking of exceptions upon discovery
4、 Data security
4.1 Sensitive Information
Explanation of inspection items
When transmitting sensitive information, it is prohibited to include sensitive information such as username, password, card number, etc. in the GET request parameters. It is recommended to use TSL encryption transmission for all sensitive information.
When the client saves sensitive information, the automatic filling function in the form and saving sensitive information in clear text are prohibited
When the server saves sensitive information, it is prohibited to hard code sensitive information in the program. Sensitive information such as user password, ID number, bank card number, and cardholder name are stored in clear text. Sensitive data temporarily written into memory or files should be cleared and released in a timely manner
When maintaining sensitive information, it is prohibited to upload source code or SQL libraries to open source platforms or communities, such as Github, Open Source China, etc.
When displaying sensitive information, if it is displayed on a web page, the sensitive fields should be desensitized on the backend server.
4.2 Log specifications
Explanation of inspection items
The recording principle ensures that the log records contain important application events, but it is prohibited to save sensitive information such as session identification, account passwords, documents, etc
Event types record all authentication, access operations, data changes, critical operations, management functions, logout records, and other events.
Event request logs typically record the occurrence time of each event, the IP address from which the request was made, and the user account (if verified).
Log protection logs are strictly protected to prevent unauthorized read or write access.
4.3 Exception Handling
Explanation of inspection items
The fault-tolerant mechanism should include a complete functional exception capture mechanism, such as a try catch block, in typical locations such as files, networks, databases, command operations, etc. during application implementation. Once an exception occurs, the occurrence time, code location, error details, and possible users who triggered the error should be fully recorded in the log. Important system serious exceptions should have an alarm mechanism, and the system operator should be notified in a timely manner to troubleshoot and fix the problem
Custom error messages In a production environment, applications should not return any system generated messages or other debugging information in their responses. Configure the application server to handle application errors that cannot be handled in a customized manner and return custom error messages
Hiding user information prohibits the disclosure of user privacy information during system abnormalities, typically including identity information, personal address, phone number, bank account, communication records, location information, etc
Hiding system information prohibits the disclosure of sensitive system information (user accounts and passwords, system development keys, system source code, application architecture, system accounts and passwords, network topology, etc.) in case of system abnormalities.
When an exception occurs, the recovery method for abnormal states should restore the previous object state, such as rollback operations when business operations fail. When object modification fails, the original state of the object should be restored to maintain consistency in the object state
5、 Host Security
5.1 I/O operation
Explanation of inspection items
When creating files in a multi user system, appropriate access permissions should be specified to prevent unauthorized file access. The read/write/executable permissions of files in the shared directory should use a whitelist mechanism to minimize authorization.
Data access checks prevent the unauthorized use of encapsulated data objects, and set reasonable data cache sizes to prevent system resource depletion,
Application file processing: Files created during the operation of the application program need to be set with permission (read, write, executable), and temporary files need to be deleted in a timely manner
5.2 Operating Environment
Explanation of inspection items
Minimize open ports and close unnecessary ports and services for the operating system
The backend service management (such as data caching and storage, monitoring, business management, etc.) is limited to internal network access, and authentication and access control must be set up for those open to the public network.
Environment configuration uses secure and stable operating system versions, various application frameworks of web server software, database components, etc
Sensitive code processing places client sensitive code (such as software package signing, username and password verification, etc.) in software packages such as o to prevent tampering.
Close the debugging channel and the production code does not contain any debugging code or interfaces
HTTPS certificate or other encryption transmission measures for communication security configuration website