保护 Web 应用免遭未经授权的 JavaScript 执行的顶级技术
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中文网其他相关文章!

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。
