Web アプリを不正な JavaScript 実行から保護するための主要なテクニック

王林
リリース: 2024-08-07 09:43:13
オリジナル
885 人が閲覧しました

Top echniques to Protect Web Apps from Unauthorized JavaScript Execution

TL;DR: 次の 5 つの重要なテクニックで Web アプリを安全に保ちます: 入力の検証とサニタイズ、コンテンツ セキュリティ ポリシーの実装、サブリソースの整合性の使用、安全性の遵守JavaScript を実践し、定期的なセキュリティ監査を実施します。 Web アプリを不正な JavaScript の実行から保護し、ユーザーを保護します。

2024 年初頭、WP Statistics、WP Meta SEO、LiteSpeed Cache などの人気の WordPress プラグインのストアド クロスサイト スクリプティング (XSS) の脆弱性を悪用した一連のサイバー攻撃が発生しました。これらの攻撃により、攻撃者は悪意のある JavaScript を挿入し、500 万を超えるアクティブなインストールを侵害することができました。

ご覧のとおり、これらの攻撃は今日の Web アプリケーションにとってかなりの脅威です。データ漏洩、個人情報の盗難、そして最終的には顧客の信頼の喪失につながる可能性があります。 HackerOne Research によると、XSS 攻撃は 2020 年に報告されたすべてのセキュリティ脅威の 23% を占め、最も頻繁に発生しました。

この記事では、不正な JavaScript の実行からアプリを保護するための 5 つのテクニックについて説明します。

1. 入力の検証とサニタイズ

これには主に、ユーザーの入力が予期された形式であるかどうかの検証が含まれます。たとえば、電子メール テキスト フィールドのデータは有効な電子メール アドレスである必要があり、ユーザー名テキスト フィールドのデータは予期されるユーザー名の構造に従っている必要があります。

サニタイズは、XSS や SQL インジェクションなどの攻撃に使用される可能性のある悪意のあるデータを除去することで、この入力をクリーンアップします。これら 2 つは、あらゆる Web アプリにとって重要なセキュリティ対策であり、ユーザーが入力する可能性のある悪意のあるデータに対する防御の第一線として機能します。

入力検証とサニタイズを実装する方法

a.クライアント側のフォーム検証

クライアント側のフォーム検証は、データ検証プロセスの最初のチェックです。ただし、JavaScript は無効化または操作され、クライアント側のチェックを簡単に回避できるため、これをセキュリティ目的のみに依存することはできません。

HTML 5 を使用した基本的なクライアント側検証の次のコード例を参照してください。

<form>
 <label for="email">Email:</label>
 <input type="email" id="email" name="email" required>
 <input type="submit" value="Submit">
</form>
ログイン後にコピー

クライアント側のフォーム検証をより包括的に確認するには、この詳細なガイドを参照してください。

b.サーバー側の検証

サーバー側の検証では、クライアント側の検証ステータスに関係なく、すべての入力が検証されることが保証されます。悪意のあるデータがコアアプリロジックやサーバー上のデータベース検証に到達しないようにすることで、セキュリティを強化します。また、改ざんに対する脆弱性も低くなります。

Express で Node.js を使用した基本的なサーバー側検証の次のコード例を参照してください。

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)

これは、XSS やデータ インジェクションなどの脅威から Web アプリを保護する強力なセキュリティ ソリューションです。 CSP を実装すると、特定の承認されたソースからのスクリプトのみが Web ページで実行できるようになります。これにより、悪意のあるコードが実行される可能性が大幅に減少します。

もっと簡単に言うと、CSP を Web アプリの用心棒として考えてください。スクリプトの出所をチェックし、信頼できるソースからのスクリプトのみを許可し、不正なスクリプトを排除します。

CSPの実装方法

CSP を実装するには、Web サーバーの HTTP 応答ヘッダーに CSP ディレクティブを追加する必要があります。 CSP ディレクティブは、Web ページ上のコンテンツのロードと実行を許可するソースをブラウザーに指示する命令です。これらのディレクティブは、さまざまな種類のリソースをきめ細かく制御できます。

主要なディレクティブには以下が含まれます:

  • default-src: すべてのコンテンツ タイプのデフォルト ポリシーを設定します。
  • script-src: JavaScript の許可されたソースを指定します。
  • style-src: スタイルシートに許可されるソースを指定します。
  • img-src: 画像の許可されるソースを指定します。
  • object-src: プラグインに許可されるソースを指定します。

HTTP 応答ヘッダーに CSP を追加する方法

Web サーバー設定を介して HTTP 応答ヘッダーに CSP を追加できます。 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 サーバーの構成にアクセスできない場合は、 タグを使用して HTML ファイルに直接 CSP を含めることができます。ただし、これは推奨される方法ではありません。

<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 コンポーネントが 1 つのパッケージに含まれているため、アプリの構築に必要な唯一のスイートです。

現在のお客様は、Essential Studio の最新バージョンをライセンスとダウンロード ページから入手できます。 Syncfusion の顧客でない場合でも、いつでも無料評価版をダウンロードしてすべてのコントロールを確認できます。

サポート フォーラム、サポート ポータル、フィードバック ポータルからもお問い合わせいただけます。いつでも喜んでお手伝いさせていただきます!

関連ブログ

  • JavaScript ファイル マネージャーでフラットな JSON データを簡単にレンダリング
  • DataManager を使用して JavaScript コントロールを簡単に同期する
  • 生産性の最適化: Salesforce と JavaScript スケジューラの統合
  • データ洞察を強化: JavaScript ガント チャートを Power BI に統合

以上がWeb アプリを不正な JavaScript 実行から保護するための主要なテクニックの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!