DEV Community

ζŸ―θ‰―ι™ˆ
ζŸ―θ‰―ι™ˆ

Posted on

network attack

I. Core Attack Types and Defenses (from a Node.js Perspective)
🧨 1. XSS (Cross-Site Scripting)

  • Principle: An attacker injects a malicious script (usually JavaScript) into your web page. When other users visit the injected page, the browser executes the malicious script. The malicious script can steal user cookies and session information, modify page content, redirect to phishing sites, or even execute actions in the user's browser.
  • Main Scenarios:
  • Stored XSS: The malicious script is persistently stored in a server database (such as user comments, posts, or profiles) and is triggered when other users visit pages containing this data.
  • Reflected XSS: The malicious script is passed to the server via URL parameters or form submissions. The server then reflects (includes) the script in the response page without processing it. This triggers the attack when the user clicks a malicious link.
  • DOM XSS: The malicious script modifies the page's DOM structure and executes directly on the client, bypassing the server. For example, malicious code can be obtained and executed through methods such as document.URL, location.hash, or document.referrer. - Node.js Defenses:
  • Output Encoding (Most Critical!): Never trust any user input! Before embedding user input in HTML, JavaScript, CSS, or URLs, it must be properly encoded.
  • HTML Context: Use the template engine's automatic escaping functionality, such as <%= variable %> (EJS) or {{ variable | escape }} (Nunjucks). This is the most common and effective approach. If manually concatenating strings, use a library like he to encode HTML entities: he.encode(userInput) .
  • JavaScript Context: When embedding data in tags or JS strings, JSON-encode it (JSON.stringify()) and ensure it is quoted, or use a dedicated JS encoding library like js-string-escape. Avoid direct concatenation.</li> <li>URL Context: Use encodeURIComponent() to encode URL parameter values.</li> <li>CSS Context: Avoid inserting user input directly into CSS. If necessary, perform strict CSS escaping or use a whitelist filter.</li> <li>Input Validation (Assistance): When receiving user input on the server, perform strict format validation (such as email address format, numeric ranges, and whitelisted characters). However, this is not a substitute for output encoding, as validation can be bypassed or may be incomplete.</li> <li>Content Security Policy (CSP): Setting a CSP policy via HTTP response headers restricts the browser to loading and executing only scripts, stylesheets, images, and other resources from trusted sources. This is a powerful defense-in-depth measure against XSS (especially stored and DOM-based XSS). It can be easily configured using the helmet-csp middleware (part of Helmet).</li> <li>Setting HttpOnly Cookies: For cookies containing sensitive session information, set the HttpOnly flag to prevent JavaScript from accessing and stealing them through document.cookie. This is key to preventing XSS session theft.</li> <li>Avoid using eval() or similar functions: Functions that dynamically execute string code, such as eval(), new Function(), setTimeout(code), and setInterval(code), are hotbeds for XSS attacks and should be avoided whenever possible. - Use modern front-end frameworks: Frameworks like React, Vue, and Angular automatically escape data by default (e.g., use {} interpolation and v-html with caution), significantly reducing the risk of XSS. However, back-end defenses are still essential. πŸ’‰ 2. SQL Injection</li> <li>How it works: An attacker injects malicious SQL code snippets into input fields (such as form fields or URL parameters), tricking the server into concatenating and executing this malicious code when executing database queries. This can lead to data leakage (stealing the entire database), data tampering (modifying or deleting data), or even server compromise.</li> <li>Node.js Defenses:</li> <li><p>Use parameterized queries/prepared statements (critical!): This is the gold standard for defending against SQL injection. Never concatenate SQL strings directly! Use the parameterized query functionality provided by your database driver or ORM (such as Sequelize, TypeORM, Prisma, or Mongoose). - Native driver example (e.g., mysql2/pg):<br> // Wrong way (vulnerable)<br> const unsafeQuery = <code>SELECT * FROM users WHERE name = &#39;${userName}&#39; AND password = &#39;${password}&#39;</code>;<br> // Correct way (parameterized query)<br> connection.query(&#39;SELECT * FROM users WHERE name = ? AND password = ?&#39;, [userName, password], (error, results) =&gt; { ... });</p></li> <li><p><strong>ORM example (e.g., Sequelize):</strong></p></li> </ul> <p>// ORM automatically handles parameterization<br> User.findOne({ where: { name: userName, password: password } }).then(user =&gt; { ... });</p> <ul> <li><strong>Input validation:</strong> Strictly validate and convert inputs expected to be in a specific format, such as numbers or dates, to specific types (e.g., <code>parseInt</code>, <code>Number</code>).</li> <li><strong>Principle of Least Privilege:</strong> Configure the user account used for database connections and grant it only the minimum permissions necessary to perform the operations required by your application (e.g., only allow <code>SELECT</code>, <code>INSERT</code>, and <code>UPDATE</code> on specific tables, and prohibit <code>DROP TABLE</code>).</li> <li><strong>Avoid dynamically concatenating table/column names:</strong> If table or column names must be dynamically determined based on user input, use a strict whitelist validation mechanism to ensure that the input contains only predefined, secure identifiers.</li> </ul> <p>πŸ”’ 3. CSRF (Cross-Site Request Forgery)</p> <ul> <li>How it works: An attacker tricks a logged-in user into sending a malicious, forged request to your website (e.g., to transfer funds, change passwords, or delete data). The browser automatically carries the user&#39;s valid cookie (session credentials) on your website, causing the server to mistakenly believe the operation is legitimate. - Node.js Defenses:</li> <li>Anti-CSRF Token (Synchronous Token Mode - Most Common): i. Generate Token: When a user accesses a protected page (such as a page containing a form), the server generates a strongly random, unique token (CSRF Token). ii. Storing the Token: The token is stored in the user&#39;s session (req.session) on the server. iii. Embed the Token: The token is embedded in an HTML form as a hidden field: <input type="hidden" name="_csrf" value="<%= csrfToken %>&quot;&gt;. For AJAX requests, the token is placed in the request header (e.g., X-CSRF-Token). iv. Verify the Token: When the server receives a state-modifying request like POST/PUT/DELETE, it extracts the token from the request body (form) or request header and compares it with the token stored in the session. The request is processed only if the two match; otherwise, it is rejected.</li> <li><p>Use Middleware: Express middleware like csurf can automate the above process. - SameSite Cookie Attribute: Set the SameSite attribute on a cookie to Strict or Lax. This prevents browsers from automatically sending cookies in cross-site requests, effectively defending against most CSRF attacks (particularly Lax, which allows cookies to be sent with GET requests during navigation but blocks them with cross-site requests like POST). This is the recommended primary defense for modern browsers and is often used in conjunction with tokens for stronger protection.<br> // Set when using cookie-session or express-session<br> app.use(session({<br> secret: &#39;your-secret&#39;,<br> cookie: {<br> secure: true, // HTTPS only<br> httpOnly: true,<br> sameSite: &#39;strict&#39; // or &#39;lax&#39;<br> }<br> }));</p></li> <li><p><strong>Verify Referer/Origin Headers (auxiliary):</strong> Checks that the <code>Referer</code> or <code>Origin</code> header in the request originates from your own domain. However, this can be forged or blocked by browser policy and should not be used as a primary defense.</p></li> </ul> <p>πŸ“ 4. File Upload Vulnerability</p> <ul> <li>Principle: If a website allows users to upload files (such as avatars, attachments, etc.), attackers may upload files containing malicious code (such as webshell .php, .jsp, .asp; executable .exe; malicious .js scripts; or .html/.svg files containing XSS). If the server is improperly configured or insecurely handled, these files may be accessed and executed, leading to server compromise, data leakage, or the spread of malware.</li> <li>Node.js Defenses:</li> <li>Strict File Type Validation:</li> <li>Check File Extensions: Use a whitelist mechanism to only allow safe extensions (such as .jpg, .png, .gif, .pdf, .docx). Blacklisting (banning certain extensions) is unreliable!</li> <li>Check MIME Type: Check req.file.mimetype (such as when using the multer middleware). However, MIME types can be forged!</li> <li>Checking File Content/Magic Numbers: Read the first few bytes of a file to verify that its true type matches the extension and MIME type. Use libraries such as file-type.</li> <li>File Content Scanning: Scan uploaded files for viruses (integrate with antivirus engines like ClamAV).</li> <li>Secure File Storage:</li> <li>File Renaming: Use randomly generated, non-patterned file names (such as a UUID + timestamp). Avoid using user-provided file names (which may contain malicious paths or characters).</li> <li>Storage Location: Store uploaded files outside the web root directory! Alternatively, configure your web server (Nginx/Apache) to prevent the execution of any script files (such as .php, .js) in the upload directory. Never set the upload directory as an executable directory.</li> <li>Permission Control: Ensure the file permissions of the upload directory are set correctly (e.g., only allow write access by the web server user, not execute access).</li> <li>File Size Limiting: To prevent DoS attacks, use middleware (such as the limits option in multer) to set a maximum upload file size. - Use dedicated middleware: Multer is a popular middleware for handling file uploads in Express. It provides features such as file size limits and file type filtering (based on MIME), but it still needs to be combined with the other measures mentioned above. πŸšͺ 5. Authentication and Session Management Vulnerabilities</li> <li>Principle: These vulnerabilities involve security issues during user login, session creation, maintenance, and destruction. Weak passwords, session fixation, session hijacking, improper session timeouts, and sensitive information leakage all fall into this category.</li> <li>Node.js Defenses:</li> <li>Strong password policy: Enforce users to use complex passwords (length, case sensitivity, numbers, and special characters). Use a slow hashing algorithm like bcrypt or argon2 to store passwords with salt (never store them in plain text!).</li> <li>Secure Session Management:</li> <li>Use a mature session middleware (such as express-session with a storage adapter like connect-mongo/connect-redis).</li> <li>Set secure cookie attributes: secure (HTTPS transmission only), httpOnly (to prevent JS access), and sameSite (to prevent CSRF).</li> <li>Set a reasonable session timeout (maxAge). - Destroy the server-side session (req.session.destroy()) when the user logs out, changes their password, or detects suspicious activity.</li> <li>Generate a strongly random, sufficiently long session ID.</li> <li>Multi-factor authentication (MFA/2FA): For sensitive operations or high-privilege accounts, enforce the use of SMS verification codes, authenticator apps (such as Google Authenticator), or hardware keys for secondary verification.</li> <li>Prevent session fixation: Regenerate the session ID (req.session.regenerate()) after the user successfully logs in.</li> <li>HTTPS: Enforce HTTPS throughout the site! Prevent session cookies and sensitive data from being eavesdropped on during transmission (man-in-the-middle attacks). Get a free certificate with Let’s Encrypt. 🧱 6. Other Important Attacks and Defenses</li> <li>Clickjacking:</li> <li>Principle: The attacker embeds your website in a malicious webpage using a transparent iframe and then carefully crafts the location to trick users into clicking on your website&#39;s content within the iframe.</li> </ul>

Top comments (0)