首頁 > web前端 > js教程 > 主體

保護 Web 應用免遭未經授權的 JavaScript 執行的頂級技術

王林
發布: 2024-08-07 09:43:13
原創
891 人瀏覽過

Top echniques to Protect Web Apps from Unauthorized JavaScript Execution

TL;DR: 使用這5 項重要技術確保您的Web 應用程式安全:驗證並清除輸入、實作內容安全策略、使用子資源完整性、遵循安全性JavaScript實踐,並定期進行安全審計。保護 Web 應用程式免受未經授權的 JavaScript 執行並保護您的使用者。

2024 年初,一系列網路攻擊利用了流行的 WordPress 外掛程式(如 WP統計、WP Meta SEO 和 LiteSpeed Cache)中儲存的跨站腳本 (XSS) 漏洞。這些攻擊允許攻擊者註入惡意 JavaScript,損害了超過 500 萬個活躍安裝。

如您所見,這些攻擊如今對 Web 應用程式構成了相當大的威脅。它們可能會導致資料外洩、身分被盜,並最終失去客戶信心。根據 HackerOne Research 的數據,XSS 攻擊佔 2020 年報告的所有安全威脅的 23%,是最常見的。

本文將介紹五種保護您的應用免受未經授權的 JavaScript 執行的技術。

1. 輸入驗證與清理

這主要涉及驗證使用者的輸入是否符合預期的格式。例如,電子郵件文字欄位中的資料應該是有效的電子郵件地址,使用者名稱文字欄位中的資料應遵循預期的使用者名稱結構。

清理透過刪除可能用於 XSS 和 SQL 注入等攻擊的任何惡意資料來清理此輸入。這兩項對於任何 Web 應用程式來說都是至關重要的安全措施,它們是防範使用者可能輸入的惡意資料的第一道防線。

如何實現輸入驗證與清理

一個。用戶端表單驗證

客戶端表單驗證是資料驗證過程的初始檢查。然而,這永遠不應該僅僅出於安全目的而依賴,因為 JavaScript 可以被停用或操縱,很容易繞過客戶端檢查。

請參考以下使用 HTML 5 進行基本用戶端驗證的程式碼範例。

<form>
 <label for="email">Email:</label>
 <input type="email" id="email" name="email" required>
 <input type="submit" value="Submit">
</form>
登入後複製

要更全面地了解客戶端表單驗證,請瀏覽此詳細指南。

b.伺服器端驗證

伺服器端驗證可確保所有輸入都經過驗證,無論客戶端驗證狀態為何。它透過確保惡意資料永遠不會到達伺服器上的核心應用程式邏輯或資料庫驗證來提高安全性。它也不易被竄改。

請參考以下使用 Node.js 和 Express 進行基本伺服器端驗證的程式碼範例。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
    const email = req.body.email;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        return res.status(400).send('Invalid email format.');
    }
    // Process the valid email.
    res.send('Email is valid!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
登入後複製

c.消毒

清理可確保刪除任何潛在有害的資料或將其變更為安全格式。以下程式碼範例使用 Node.js 中的驗證器庫來清理輸入。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const validator = require('validator');

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
    let email = req.body.email;
    if (!validator.isEmail(email)) {
        return res.status(400).send('Invalid email format.');
    }
    email = validator.normalizeEmail(email);
    // Process the sanitized email
    res.send('Email is valid and sanitized!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
登入後複製

2. 內容安全策略(CSP)

這是一個強大的安全解決方案,可保護 Web 應用程式免受 XSS 和資料注入等威脅。實作 CSP 可確保只有來自特定、經批准的來源的腳本才能在您的網頁上運作。這顯著降低了惡意程式碼執行的機會。

簡單來說,將 CSP 視為您的 Web 應用程式的保鑣。它檢查腳本的來源,只允許來自可信來源的腳本,將不良腳本拒之門外。

如何實施CSP

實作 CSP 涉及將 CSP 指令新增至 Web 伺服器的 HTTP 回應標頭。 CSP 指令是告訴瀏覽器允許哪些來源載入和執行網頁上的內容的指令。這些指令提供對各種類型資源的精細控制。

主要指令包括:

  • default-src: 為所有內容類型設定預設策略。
  • script-src: 指定允許的 JavaScript 來源。
  • style-src: 指定樣式表允許的來源。
  • img-src: 指定允許的影像來源。
  • object-src: 指定外掛允許的來源。

如何將CSP加入到HTTP回應標頭

您可以透過 Web 伺服器設定將 CSP 新增至 HTTP 回應標頭。請參閱以下程式碼範例在 Apache 伺服器中設定 CSP。

Header set Content-Security-Policy "default-src 'self'; img-src *"
登入後複製

對於Nginx,您可以如下設定CSP。

add_header Content-Security-Policy "default-src 'self'; img-src *"
登入後複製

如何透過元標記添加 CSP

如果您無法存取 Web 伺服器的配置,您可以使用 標籤將 CSP 直接包含在 HTML 檔案中。但這不是推薦的方式。

<head>
 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src *"">
</head>
登入後複製

3. Sub-resource integrity (SRI)

This security feature helps browsers check if the resources obtained from a third party (for instance, a CDN) have been modified. It allows you to provide a cryptographic hash for these resources.

When the browser gets the resource, it compares its hash to the given hash. If the hash does not match, the resources will not be loaded, thereby protecting your app from malicious modifications.

How to implement SRI

Implementing SRI involves adding a cryptographic hash to the integrity attribute of your or tags. Here’s a step-by-step guide to setting up SRI:

Step 1: Generating the hash

You must generate a hash for the resource you want to include in your webpage. This can be done using a tool or online service like the Subresource Integrity Generator tool.

Step 2: Adding the hash to your resource

Once you have the hash, add it to the integrity attribute of the or < link> tag.

Refer to the following code example.

<script src="https://example.com/script.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxqAtD6x48V2aB1xzA7e2h53sF2aAuM" crossorigin="anonymous"></script>
登入後複製

In this example, the integrity attribute contains the hash, and the crossorigin=”anonymous” attribute ensures the resource is fetched with CORS (cross-origin resource sharing).

You can use SRI for stylesheets, as well.

<link rel="stylesheet" href="https://example.com/styles.css" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxqAtD6x48V2aB1xzA7e2h53sF2aAuM" crossorigin="anonymous">
登入後複製

4. Secure JavaScript coding practices

Secure JavaScript coding practices are crucial for developing web apps robust against various attacks, XSS, and other malicious exploits. By following these best practices, developers can ensure their code is secure, maintainable, and less vulnerable to unauthorized execution.

Avoid using eval()

The eval() function is a significant security risk, as it executes a string of code, potentially allowing attackers to inject malicious scripts. Always avoid using eval() and similar functions like setTimeout(string) and setInterval(string).

Why these functions are dangerous:

  • Arbitrary code execution: These functions can execute any code passed to them as a string. If an attacker successfully inserts a malicious string, it will operate in the same way as the remaining code of your script.
  • Difficulty in code analysis: Using these functions makes it harder to analyze the code for security vulnerabilities. Static analysis tools cannot examine the strings that are passed through such functions.
  • Dynamic code injection: Attackers can use these functions to inject and execute code dynamically that was not originally part of the app, bypassing traditional security measures.

Use strict mode

Enabling strict mode in JavaScript helps catch common coding mistakes and unsafe actions, such as assigning values to undeclared variables. This improves the security and stability of your code. To enable strict mode, add “use strict”; at the beginning of a script or a function.

"use strict";

function safeFunction() {
    // Code in strict mode.
    let secureVariable = "Secure";
    console.log(secureVariable);
}

safeFunction();
登入後複製

Advantages and implications of enabling strict mode:

  • In strict mode, this is undefined in functions that are not called methods.
  • Strict mode will throw an error if a function has duplicate parameter names or an object literal has duplicate property names.
  • A with statement is not allowed in the strict mode because it makes code difficult to predict and optimize.

Refer to the following code example.

"use strict";

// Eliminates this coercion.
function showThis() {
    console.log(this); // In non-strict mode, this would be the global object; in strict mode, it's undefined.
}
showThis();

// Disallows duplicate property names or parameter values.
// This will throw an error in strict mode.
const obj = {
    prop: 1,
    prop: 2
};

// Prevents the use of with statement.
// This will throw an error in strict mode.
with (Math) {
    let x = cos(3.14);
}
登入後複製

Avoid inline JavaScript

Inline JavaScript can be significantly vulnerable to XSS attacks because it allows attackers to inject malicious scripts directly into your HTML. Instead, use external scripts to ensure all JavaScript is properly vetted and sanitized.

Avoid inline JavaScript because of:

  • Ease of injection: Inline JavaScript is more susceptible to injection attacks because it is part of the HTML content.
  • CSP compliance: Content security policies (CSP) can be more effectively enforced when JavaScript is kept in external files. Inline scripts often require the use of the unsafe-inline directive, which weakens CSP’s effectiveness.
  • Maintainability: Keeping JavaScript in separate files makes the codebase easier to manage and maintain.

Refer to the following code example.

<!-- Insecure Inline JavaScript -->
<!-- <button onclick="alert('Clicked!')">Click Me</button> -->

<!-- Secure External JavaScript -->
<button id="secureButton">Click Me</button>
<script>
    document.getElementById('secureButton').addEventListener('click', function() {
        alert('Clicked!');
    });
</script>
登入後複製

5. Regular Security Audits and Updates

Regular audits are essential for maintaining the integrity and security of web apps. By continuously assessing your app’s security, you can identify and fix vulnerabilities that could be exploited to execute unauthorized JavaScript or other malicious actions.

如何進行定期安全審計

自動安全掃描

使用 OWASP ZAP 或 Burp Suite 等工具掃描已知漏洞。自動掃描提供了識別常見安全問題的快速方法。

手動程式碼審查

定期手動檢查您的程式碼庫,以發現自動化工具可能遺漏的問題。為此,最好使用經驗豐富的開發人員和安全專家。

滲透測試

聘請滲透測試人員模擬對您的應用程式的攻擊,發現其他方法可能無法偵測到的漏洞。

更新依賴項

保持您的依賴更新,以修復庫和框架中的已知漏洞。使用 NPM 或 pip 等套件管理器來管理更新。

安全訓練

持續訓練您的開發團隊了解最新的安全實務和常見漏洞。這將確保您的團隊有能力編寫安全的程式碼。

結論性想法

感謝您閱讀這篇文章。我們希望這 5 種技術能夠增強您的應用程式對未經授權的 JavaScript 執行的防禦能力。透過實施這些策略,您可以降低攻擊風險並確保為使用者提供更安全的 Web 應用程式。請記住,在安全措施方面保持主動和警惕是保護您的數位資產的關鍵。

Syncfusion JavaScript UI 控制項庫是您建立應用程式所需的唯一套件,因為它在單一套件中包含超過 85 個高效能、輕量級、模組化和響應式 UI 元件。

對於目前客戶,可以從授權和下載頁面取得最新版本的 Essential Studio。如果您不是 Syncfusion 客戶,您可以隨時下載我們的免費評估版以查看我們的所有控制項。

您也可以透過我們的支援論壇、支援入口網站或回饋入口網站聯絡我們。我們很樂意為您提供協助!

相關部落格

  • 在 JavaScript 檔案管理器中輕鬆渲染平面 JSON 資料
  • 使用 DataManager 輕鬆同步 JavaScript 控制項
  • 最佳化生產力:將 Salesforce 與 JavaScript Scheduler 整合
  • 增強資料洞察力:將 JavaScript 甘特圖整合到 Power BI

以上是保護 Web 應用免遭未經授權的 JavaScript 執行的頂級技術的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!