신뢰할 수 없는 JavaScript 코드 실행

WBOY
풀어 주다: 2024-07-22 07:10:29
원래의
1057명이 탐색했습니다.

Running Untrusted JavaScript Code

중요: 이것은 JavaScript 및 TypeScript 코드 실행에만 해당됩니다. 즉, 글을 쓰는 것이 다른 언어에서 다른 코드를 실행하는 방향이 될 수도 있습니다.

사용자가 애플리케이션 내에서 코드를 실행할 수 있도록 허용하면 사용자 정의 및 기능의 세계가 열리지만 동시에 플랫폼이 심각한 보안 위협에 노출됩니다.

사용자 코드인 점을 고려하면 서버 정지(무한 루프일 수 있음)부터 민감한 정보 도용까지 모든 것이 예상됩니다.

이 기사에서는 웹 워커, 정적 코드 분석 등을 포함하여 사용자 코드 실행을 완화하기 위한 다양한 전략을 살펴보겠습니다.

당신은 관심을 가져야합니다

CodeSandbox 및 StackBiltz와 같은 공동 개발 환경부터 January와 같은 사용자 정의 가능한 API 플랫폼에 이르기까지 사용자 제공 코드를 실행해야 하는 시나리오는 많습니다. 코드 플레이그라운드도 위험에 노출되어 있습니다.

즉, 사용자 제공 코드를 안전하게 실행하는 데 있어 두 가지 중요한 이점은 다음과 같습니다.

  1. 사용자의 신뢰 얻기: 사용자가 신뢰할 만하더라도 의도적으로 악의적인 사람이 복사한 코드를 실행할 수 있습니다.
  2. 환경 보호: 마지막으로 필요한 것은 서버를 정지시키는 코드입니다. 생각하는 동안(true) {}

"민감한 정보"를 정의하세요

일부 데이터가 도난당할 수 있다는 우려가 있을 때까지 사용자 코드를 실행하는 것은 해롭지 않습니다. 귀하가 우려하는 모든 데이터는 민감한 정보로 간주됩니다. 예를 들어 대부분의 경우 JWT는 민감한 정보입니다(아마도 인증 메커니즘으로 사용되는 경우)

무엇이 잘못될 수 있나요?

모든 요청과 함께 전송되는 쿠키에 저장된 JWT의 잠재적 위험을 고려하세요. 사용자가 JWT를 악의적인 서버로 보내는 요청을 실수로 트리거할 수 있으며...

  • 교차 사이트 스크립팅(XSS).
  • 서비스 거부(DoS) 공격.
  • 데이터 유출. 적절한 보호 장치가 없으면 이러한 위협으로 인해 애플리케이션의 무결성과 성능이 손상될 수 있습니다.

행동 양식

사악한 평가

가장 단순하지만 가장 위험합니다.

eval('console.log("I am dangerous!")');
로그인 후 복사

이 코드를 실행하면 해당 메시지가 기록됩니다. 기본적으로 eval은 전역/창 범위에 액세스할 수 있는 JS 인터프리터입니다.

const res = await eval('fetch(`https://jsonplaceholder.typicode.com/users`)');
const users = await res.json();
로그인 후 복사

이 코드는 전역 범위에 정의된 가져오기를 사용합니다. 인터프리터는 이에 대해 모르지만 eval이 창에 액세스할 수 있으므로 알고 있습니다. 이는 브라우저에서 평가판을 실행하는 것이 서버 환경이나 작업자에서 실행하는 것과 다르다는 것을 의미합니다.

eval(`document.body`);
로그인 후 복사

이건 어때요...

eval(`while (true) {}`);
로그인 후 복사

이 코드는 브라우저 탭을 중지합니다. 사용자가 왜 스스로에게 이런 짓을 하는지 물을 수도 있습니다. 글쎄, 그들은 인터넷에서 코드를 복사하고 있을 수도 있습니다. 이것이 바로 정적 분석을 수행하거나 실행 시간을 제한하는 것이 선호되는 이유입니다.

평가에 관한 MDN Docs를 확인해 보세요

타임박스 실행은 웹 워커에서 코드를 실행하고 setTimeout을 사용해 실행 시간을 제한하는 방식으로 수행할 수 있습니다.

async function timebox(code, timeout = 5000) {
  const worker = new Worker('user-runner-worker.js');
  worker.postMessage(code);

  const timerId = setTimeout(() => {
    worker.terminate();
    reject(new Error('Code execution timed out'));
  }, timeout);

  return new Promise((resolve, reject) => {
    worker.onmessage = event => {
      clearTimeout(timerId);
      resolve(event.data);
    };
    worker.onerror = error => {
      clearTimeout(timerId);
      reject(error);
    };
  });
}

await timebox('while (true) {}');
로그인 후 복사

함수 생성자

eval과 비슷하지만, 바깥쪽 스코프에 접근할 수 없기 때문에 좀 더 안전합니다.

const userFunction = new Function('param', 'console.log(param);');
userFunction(2);
로그인 후 복사

이 코드는 2를 기록합니다.

참고: 두 번째 인수는 함수 본문입니다.

함수 생성자가 바깥쪽 범위에 액세스할 수 없으므로 다음 코드에서 오류가 발생합니다.

function fnConstructorCannotUseMyScope() {
  let localVar = 'local value';
  const userFunction = new Function('return localVar');
  return userFunction();
}
로그인 후 복사

하지만 전역 범위에 액세스할 수 있으므로 위의 가져오기 예시가 작동합니다.

웹워커

WebWorker에서 "Function Constructor 및 eval"을 실행할 수 있는데, 이는 DOM 액세스가 없기 때문에 조금 더 안전합니다.

더 많은 제한을 적용하려면 fetch, XMLHttpRequest, sendBeacon과 같은 전역 개체 사용을 허용하지 않는 것이 좋습니다. 이를 수행하는 방법에 대해서는 이 글을 확인하세요.

격리된 VM

Isolated-VM은 별도의 VM(v8의 Isolate 인터페이스)에서 코드를 실행할 수 있는 라이브러리입니다

import ivm from 'isolated-vm';

const code = `count += 5;`;

const isolate = new ivm.Isolate({ memoryLimit: 32 /* MB */ });
const script = isolate.compileScriptSync(code);
const context = isolate.createContextSync();

const jail = context.global;
jail.setSync('log', console.log);

context.evalSync('log("hello world")');
로그인 후 복사

이 코드는 hello world를 기록합니다

웹어셈블리

코드 실행을 위한 샌드박스 환경을 제공한다는 점에서 흥미로운 옵션입니다. 한 가지 주의할 점은 Javascript 바인딩이 있는 환경이 필요하다는 것입니다. 그러나 Extism이라는 흥미로운 프로젝트가 이를 촉진합니다. 튜토리얼을 따라해 보세요.

흥미로운 점은 코드를 실행하기 위해 공기압을 사용한다는 것입니다. 그러나 WebAssembly의 특성상 DOM, 네트워크, 파일 시스템 및 호스트 환경에 대한 액세스가 불가능합니다(물론 환경에 따라 다를 수 있음). wasm 런타임).

function evaluate() {
  const { code, input } = JSON.parse(Host.inputString());
  const func = eval(code);
  const result = func(input).toString();
  Host.outputString(result);
}

module.exports = { evaluate };
로그인 후 복사

You'll have to compile the above code first using Extism, which will output a Wasm file that can be run in an environment that has Wasm-runtime (browser or node.js).

const message = {
  input: '1,2,3,4,5',
  code: `
        const sum = (str) => str
          .split(',')
          .reduce((acc, curr) => acc + parseInt(curr), 0);
        module.exports = sum;
`,
};

// continue running the wasm file
로그인 후 복사

Docker

We're now moving to the server-side, Docker is a great option to run code in an isolation from the host machine. (Beware of container escape)

You can use dockerode to run the code in a container.

import Docker from 'dockerode';
const docker = new Docker();

const code = `console.log("hello world")`;
const container = await docker.createContainer({
  Image: 'node:lts',
  Cmd: ['node', '-e', code],
  User: 'node',
  WorkingDir: '/app',
  AttachStdout: true,
  AttachStderr: true,
  OpenStdin: false,
  AttachStdin: false,
  Tty: true,
  NetworkDisabled: true,
  HostConfig: {
    AutoRemove: true,
    ReadonlyPaths: ['/'],
    ReadonlyRootfs: true,
    CapDrop: ['ALL'],
    Memory: 8 * 1024 * 1024,
    SecurityOpt: ['no-new-privileges'],
  },
});
로그인 후 복사

Keep in mind that you need to make sure the server has docker installed and running. I'd recommend having a separate server dedicated only to this that acts as a pure-function server.

Moreover, you might benefit from taking a look at sysbox, a VM-like container runtime that provides a more secure environment. Sysbox is worth it, especially if the main app is running in a container, which means that you'll be running Docker in Docker.

This was the method of choice at January but soon enough, the language capabilities mandated more than passing the code through the container shell. Besides, for some reason, the server memory spikes frequently; we run the code inside self-removable containers on every 1s debounced keystroke. (You can do better!)

Other options

  • Web Containers
  • MicroVM (Firecraker)
  • Deno subhosting
  • Wasmer
  • ShadowRealms

Safest option

I'm particularly fond of Firecracker, but it’s a bit of work to set up, so if you cannot afford the time yet, you want to be on the safe side, do a combination of static analysis and time-boxing execution. You can use esprima to parse the code and check for any malicious act.

How to run TypeScript code?

Well, same story with one (could be optional) extra step: Transpile the code to JavaScript before running it. Simply put, you can use esbuild or typescript compiler, then continue with the above methods.

async function build(userCode: string) {
  const result = await esbuild.build({
    stdin: {
      contents: `${userCode}`,
      loader: 'ts',
      resolveDir: __dirname,
    },
    inject: [
      // In case you want to inject some code
    ],
    platform: 'node',
    write: false,
    treeShaking: false,
    sourcemap: false,
    minify: false,
    drop: ['debugger', 'console'],
    keepNames: true,
    format: 'cjs',
    bundle: true,
    target: 'es2022',
    plugins: [
      nodeExternalsPlugin(), // make all the non-native modules external
    ],
  });
  return result.outputFiles![0].text;
}
로그인 후 복사

Notes:

  • Rust-based bundlers usually offer a web assembly version, which means you can transpile the code in the browser. Esbuild does have a web assembly version.
  • Don't include user specified imports into the bundle unless you've allow-listed them.

Additionally, you can avoid transpiling altogether by running the code using Deno or Bun in a docker container since they support TypeScript out of the box.

Conclusion

Running user code is a double-edged sword. It can provide a lot of functionality and customization to your platform, but it also exposes you to significant security risks. It’s essential to understand the risks and take appropriate measures to mitigate them and remember that the more isolated the environment, the safer it is.

References

  • January instant compilation
  • Running untrusted JavaScript in Node.js
  • How do languages support executing untrusted user code at runtime?
  • Safely Evaluating JavaScript with Context Data

위 내용은 신뢰할 수 없는 JavaScript 코드 실행의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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