Teknik teratas untuk Melindungi Apl Web daripada Perlaksanaan JavaScript Tanpa Kebenaran

王林
Lepaskan: 2024-08-07 09:43:13
asal
799 orang telah melayarinya

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 を使用した基本的なクライアント側検証の次のコード例を参照してください。


リーリー

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

b.サーバー側の検証

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

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

リーリー
c.消毒

サニタイズにより、潜在的に有害なデータが削除されるか、安全な形式に変更されます。次のコード例では、Node.js のバリデーター ライブラリを使用して入力をサニタイズします

リーリー
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 を設定するには、次のコード例を参照してください。

リーリー
Nginx

の場合、次のようにCSPを構成できます。

リーリー メタタグを介して CSP を追加する方法

Web サーバーの設定にアクセスできない場合は、

タグを使用して HTML ファイルに直接 CSP を含めることができます。ただし、これは推奨される方法ではありません。

<head>
 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src *"">
</head>
Salin selepas log masuk

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>
Salin selepas log masuk

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">
Salin selepas log masuk

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();
Salin selepas log masuk

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);
}
Salin selepas log masuk

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>
Salin selepas log masuk

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.

Bagaimana untuk menjalankan audit keselamatan secara berkala

Pengimbasan keselamatan automatik

Gunakan alatan seperti OWASP ZAP atau Burp Suite untuk mengimbas kelemahan yang diketahui. Imbasan automatik menyediakan cara cepat untuk mengenal pasti isu keselamatan biasa.

Ulasan kod manual

Semak semula pangkalan kod anda secara manual untuk mengetahui isu yang mungkin terlepas oleh alatan automatik. Adalah lebih baik untuk menggunakan pembangun berpengalaman dan pakar keselamatan untuk ini.

Ujian penembusan

Upah penguji penembusan untuk mensimulasikan serangan pada apl anda, mendedahkan kelemahan yang mungkin tidak dapat dikesan oleh kaedah lain.

Kemas kini kebergantungan

Pastikan kebergantungan anda dikemas kini untuk membetulkan kelemahan yang diketahui dalam perpustakaan dan rangka kerja. Gunakan pengurus pakej seperti NPM atau pip untuk mengurus kemas kini.

Latihan keselamatan

Latih pasukan pembangunan anda secara berterusan tentang amalan keselamatan terkini dan kelemahan biasa. Ini akan memastikan pasukan anda dilengkapi untuk menulis kod selamat.

Menyimpulkan pemikiran

Terima kasih kerana membaca artikel ini. Kami berharap 5 teknik ini meningkatkan pertahanan apl anda terhadap pelaksanaan JavaScript yang tidak dibenarkan. Dengan melaksanakan strategi ini, anda boleh mengurangkan risiko serangan dan memastikan apl web yang lebih selamat dan selamat untuk pengguna anda. Ingat, kekal proaktif dan berwaspada dalam langkah keselamatan anda adalah kunci untuk melindungi aset digital anda.

Pustaka kawalan UI JavaScript Syncfusion ialah satu-satunya suite yang anda perlukan untuk membina apl kerana ia mengandungi lebih 85 komponen UI berprestasi tinggi, ringan, modular dan responsif dalam satu pakej.

Untuk pelanggan semasa, versi terbaru Essential Studio tersedia daripada halaman Lesen dan Muat Turun. Jika anda bukan pelanggan Syncfusion, anda sentiasa boleh memuat turun penilaian percuma kami untuk melihat semua kawalan kami.

Anda juga boleh menghubungi kami melalui forum sokongan, portal sokongan atau portal maklum balas kami. Kami sentiasa berbesar hati untuk membantu anda!

Blog berkaitan

  • Membuat Data JSON Rata dengan Mudah dalam Pengurus Fail JavaScript
  • Segerakkan Kawalan JavaScript Dengan Mudah Menggunakan DataManager
  • Mengoptimumkan Produktiviti: Mengintegrasikan Salesforce dengan Penjadual JavaScript
  • Memperkasakan Cerapan Data Anda: Mengintegrasikan Carta Gantt JavaScript ke dalam Power BI

Atas ialah kandungan terperinci Teknik teratas untuk Melindungi Apl Web daripada Perlaksanaan JavaScript Tanpa Kebenaran. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!