6.16 Prevent malicious RegEx from overloading your single thread execution

고준영·2021년 11월 30일
0

Nodebestpractices

목록 보기
10/16
post-thumbnail

Prevent malicious RegEx from overloading your single thread execution

One Paragraph Explainer

The risk that is inherent with the use of Regular Expressions is the computational resources that require to parse text and match a given pattern. For the Node.js platform, where a single-thread event-loop is dominant, a CPU-bound operation like resolving a regular expression pattern will render the application unresponsive.
Avoid RegEx when possible or defer the task to a dedicated library like validator.js, or safe-regex to check if the RegEx pattern is safe.

Some OWASP examples for vulnerable RegEx patterns:

  • (a|aa)+
  • ([a-zA-Z]+)*



Code Example – Enabling SSL/TLS using the Express framework

const saferegex = require('safe-regex');
const emailRegex = /^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$/;

// should output false because the emailRegex is vulnerable to redos attacks
console.log(saferegex(emailRegex));

// instead of the regex pattern, use validator:
const validator = require('validator');
console.log(validator.isEmail('liran.tal@gmail.com'));



Book Quote: "A vulnerable Regular Expression is known as one which applies repetition"

From the book Essential Node.js Security by Liran Tal

Often, programmers will use RegEx to validate that an input received from a user conforms to an expected condition. A vulnerable Regular Expression is known as one which applies repetition to a repeating capturing group, and where the string to match is composed of a suffix of a valid matching pattern plus characters that aren't matching the capturing group.


6.16 악성 정규표현(RegEx)이 단일 스레드 실행을 과부하시키는것을 막아라

한문단 요약

정규식을 사용하는데 있어 내제된 위험은 텍스트를 분석하고 주어진 정규식 패턴과 일치하는지 확인하는데 필요한 계산 리소스이다.
단일 스레드 이벤트 루프가 지배적인 Node.js 플랫폼의 경우 정규식 패턴을 확인하는 것과 같은 CPU를 사용하는 작업은 애플리케이션이 응답하지 않을 수 있게 한다.

가능하면 정규식 사용을 피하거나 정규식 패턴이 안전한지 확인하는 작업을 validator.js, 또는 safe-regex와 같은 전용 라이브러리로 미뤄라.

OWASP 예시에 있는 취약한 정규식 패턴 몇가지:

  • (a|aa)+
  • ([a-zA-Z]+)*



예시코드 – Express 프레임워크를 사용하여 SSL/TLS 활성화하기

const saferegex = require('safe-regex');
const emailRegex = //^/([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))/$//;

/// email정규식은 redos 공격에 취약하기 때문에 false를 출력해야 한다./
console.log(saferegex(emailRegex));

/// 정규식 패턴 대신 유효성 검사기를 사용해라/
const validator = require('validator');
console.log(validator.isEmail('liran.tal@gmail.com'));

SSL/TLS -> 암호화, 인증, 무결성을 보장한다.
위의 예에서는 무결성을 부여함.
https의 기술임
인증서를 사용해서 암호화 복호화 한다.



책 인용: “취약한 정규식은 반복을 적용하는 것으로 알려져 있다.”

Liran Tal의 필수 Node.js 보안에서 발췌
/> 프로그래머는 종종 정규식을 사용하여 사용자의 입력이 조건에 부합하는지 확인하는 작업을 한다. 취약한 정규식은 반복의 연속과 일치하는 접미사 패턴과 +의 조합으로 알려져 있다./

profile
코드짜는귤🍊 풀스택을 지향하는 주니어 개발자 입니다🧡

0개의 댓글