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

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 进行基本客户端验证的代码示例。


要更全面地了解客户端表单验证,请浏览此详细指南。

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 文件中。但这不是推荐的方式。

 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src *">

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
在JavaScript中替换字符串字符在JavaScript中替换字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

自定义Google搜索API设置教程自定义Google搜索API设置教程Mar 04, 2025 am 01:06 AM

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

构建您自己的Ajax Web应用程序构建您自己的Ajax Web应用程序Mar 09, 2025 am 12:11 AM

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

示例颜色json文件示例颜色json文件Mar 03, 2025 am 12:35 AM

本文系列在2017年中期进行了最新信息和新示例。 在此JSON示例中,我们将研究如何使用JSON格式将简单值存储在文件中。 使用键值对符号,我们可以存储任何类型的

10个jQuery语法荧光笔10个jQuery语法荧光笔Mar 02, 2025 am 12:32 AM

增强您的代码演示:开发人员的10个语法荧光笔 在您的网站或博客上共享代码片段是开发人员的常见实践。 选择合适的语法荧光笔可以显着提高可读性和视觉吸引力。 t

8令人惊叹的jQuery页面布局插件8令人惊叹的jQuery页面布局插件Mar 06, 2025 am 12:48 AM

利用轻松的网页布局:8个基本插件 jQuery大大简化了网页布局。 本文重点介绍了简化该过程的八个功能强大的JQuery插件,对于手动网站创建特别有用

10 JavaScript和JQuery MVC教程10 JavaScript和JQuery MVC教程Mar 02, 2025 am 01:16 AM

本文介绍了关于JavaScript和JQuery模型视图控制器(MVC)框架的10多个教程的精选选择,非常适合在新的一年中提高您的网络开发技能。 这些教程涵盖了来自Foundatio的一系列主题

什么是这个&#x27;在JavaScript?什么是这个&#x27;在JavaScript?Mar 04, 2025 am 01:15 AM

核心要点 JavaScript 中的 this 通常指代“拥有”该方法的对象,但具体取决于函数的调用方式。 没有当前对象时,this 指代全局对象。在 Web 浏览器中,它由 window 表示。 调用函数时,this 保持全局对象;但调用对象构造函数或其任何方法时,this 指代对象的实例。 可以使用 call()、apply() 和 bind() 等方法更改 this 的上下文。这些方法使用给定的 this 值和参数调用函数。 JavaScript 是一门优秀的编程语言。几年前,这句话可

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境