무단 JavaScript 실행으로부터 웹 앱을 보호하는 주요 기술

王林
풀어 주다: 2024-08-07 09:43:13
원래의
850명이 탐색했습니다.

Top echniques to Protect Web Apps from Unauthorized JavaScript Execution

TL;DR: 입력 유효성 검사 및 삭제, 콘텐츠 보안 정책 구현, 하위 리소스 무결성 사용, 보안 준수 등 5가지 필수 기술로 웹 앱을 안전하게 유지하세요. JavaScript를 실천하고 정기적인 보안 감사를 실시합니다. 승인되지 않은 JavaScript 실행으로부터 웹 앱을 보호하고 사용자를 보호하세요.

2024년 초, WP Statistics, WP Meta SEO, LiteSpeed ​​Cache와 같은 인기 WordPress 플러그인에 저장된 XSS(교차 사이트 스크립팅) 취약점을 악용한 일련의 사이버 공격이 발생했습니다. 이러한 공격을 통해 공격자는 악성 JavaScript를 주입하여 5백만 개가 넘는 활성 설치를 손상시킬 수 있었습니다.

보시다시피 이러한 공격은 오늘날 웹 애플리케이션에 상당한 위협이 됩니다. 이로 인해 데이터 유출, 신원 도용, 궁극적으로 고객 신뢰 상실이 발생할 수 있습니다. HackerOne Research에 따르면 XSS 공격은 2020년에 보고된 모든 보안 위협의 23%를 차지하여 가장 빈번하게 발생했습니다.

이 문서에서는 승인되지 않은 JavaScript 실행으로부터 앱을 보호하는 5가지 기술을 설명합니다.

1. 입력 검증 및 정리

여기에는 주로 사용자의 입력이 예상 형식 내에 있는지 확인하는 작업이 포함됩니다. 예를 들어 이메일 텍스트 필드의 데이터는 유효한 이메일 주소여야 하며 사용자 이름 텍스트 필드의 데이터는 예상되는 사용자 이름 구조를 따라야 합니다.

삭제 작업은 XSS 및 SQL 삽입과 같은 공격에 사용될 수 있는 모든 악성 데이터를 제거하여 이 입력을 정리합니다. 이 두 가지는 모든 웹 앱에 대한 중요한 보안 조치이며 사용자가 입력할 수 있는 악성 데이터에 대한 첫 번째 방어선 역할을 합니다.

입력 유효성 검사 및 삭제를 구현하는 방법

에이. 클라이언트측 양식 유효성 검사

클라이언트측 양식 유효성 검사는 데이터 유효성 검사 프로세스의 초기 확인입니다. 그러나 JavaScript는 비활성화되거나 조작되어 클라이언트 측 검사를 쉽게 우회할 수 있으므로 보안 목적으로만 이에 의존해서는 안 됩니다.

HTML 5를 사용한 기본 클라이언트측 유효성 검사에 대한 다음 코드 예제를 참조하세요.

<form>
 <label for="email">Email:</label>
 <input type="email" id="email" name="email" required>
 <input type="submit" value="Submit">
</form>
로그인 후 복사

클라이언트측 양식 유효성 검사에 대해 더 포괄적으로 살펴보려면 이 세부 가이드를 살펴보세요.

비. 서버측 검증

서버측 검증은 클라이언트측 검증 상태에 관계없이 모든 입력의 검증을 보장합니다. 악성 데이터가 서버의 핵심 앱 논리 또는 데이터베이스 유효성 검사에 도달하지 않도록 보장하여 보안을 강화합니다. 변조에도 덜 취약합니다.

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');
});
로그인 후 복사

기음. 살균

위생 처리를 통해 잠재적으로 유해한 데이터가 제거되거나 안전한 형식으로 변경됩니다. 다음 코드 예제는 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, 데이터 주입 등의 위협으로부터 웹앱을 보호하는 강력한 보안 솔루션입니다. CSP를 구현하면 승인된 특정 소스의 스크립트만 웹 페이지에서 실행할 수 있습니다. 이로써 악성코드 실행 가능성이 대폭 줄어듭니다.

간단히 말하면 CSP를 웹 앱의 경비원이라고 생각하세요. 스크립트의 출처를 확인하고 신뢰할 수 있는 소스의 스크립트만 허용하여 잘못된 스크립트는 차단합니다.

CSP 구현 방법

CSP를 구현하려면 웹 서버의 HTTP 응답 헤더에 CSP 지시문을 추가해야 합니다. CSP 지시문은 웹페이지에서 콘텐츠를 로드하고 실행하도록 허용된 소스를 브라우저에 알려주는 지침입니다. 이러한 지시어는 다양한 유형의 리소스에 대한 세부적인 제어를 제공합니다.

주요 지침은 다음과 같습니다.

  • default-src: 모든 콘텐츠 유형에 대한 기본 정책을 설정합니다.
  • script-src: JavaScript에 허용되는 소스를 지정합니다.
  • style-src: 스타일시트에 허용되는 소스를 지정합니다.
  • img-src: 허용되는 이미지 소스를 지정합니다.
  • object-src: 플러그인에 허용되는 소스를 지정합니다.

HTTP 응답 헤더에 CSP를 추가하는 방법

웹 서버 구성을 통해 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를 추가하는 방법

웹 서버 구성에 액세스할 수 없는 경우 태그를 사용하여 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 실행에 대한 앱의 방어력을 강화하기를 바랍니다. 이러한 전략을 구현하면 공격 위험을 줄이고 사용자에게 더욱 안전한 웹 앱을 제공할 수 있습니다. 디지털 자산을 보호하려면 보안 조치에 적극적이고 주의를 기울이는 것이 중요합니다.

Syncfusion JavaScript UI 컨트롤 라이브러리는 단일 패키지에 85개 이상의 고성능, 경량, 모듈식 및 반응형 UI 구성 요소가 포함되어 있으므로 앱을 구축하는 데 필요한 유일한 제품군입니다.

현재 고객의 경우 라이선스 및 다운로드 페이지에서 최신 버전의 Essential Studio를 다운로드할 수 있습니다. Syncfusion 고객이 아닌 경우 언제든지 무료 평가판을 다운로드하여 모든 컨트롤을 확인할 수 있습니다.

지원 포럼, 지원 포털 또는 피드백 포털을 통해 문의하실 수도 있습니다. 우리는 언제나 기꺼이 당신을 도와드리겠습니다!

관련 블로그

  • JavaScript 파일 관리자에서 플랫 JSON 데이터를 쉽게 렌더링
  • DataManager를 사용하여 JavaScript 컨트롤을 손쉽게 동기화
  • 생산성 최적화: Salesforce와 JavaScript 스케줄러 통합
  • 데이터 통찰력 강화: JavaScript Gantt Chart를 Power BI에 통합

위 내용은 무단 JavaScript 실행으로부터 웹 앱을 보호하는 주요 기술의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!