首页 >web前端 >js教程 >保护 Web 应用免遭未经授权的 JavaScript 执行的顶级技术

保护 Web 应用免遭未经授权的 JavaScript 执行的顶级技术

王林
王林原创
2024-08-07 09:43:13984浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn