programing

문자열로 저장된 JavaScript 코드 실행

copysource 2023. 2. 3. 23:05
반응형

문자열로 저장된 JavaScript 코드 실행

문자열인 JavaScript를 실행하려면 어떻게 해야 하나요?

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    // how do I get a browser to alert('hello')?
}

다음과 같은 기능이 있습니다.

eval("my script here");

함수를 사용하여 실행할 수 있습니다.예:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

함수는 전달된 문자열을 평가합니다.

그러나 의 사용매우 위험하고 느리므로 주의하여 사용하십시오.

노드를 사용하고 있으며 다음 컨텍스트의 영향을 우려하는 사용자용eval()nodejs 제공vm. 별도의 컨텍스트에서 코드 실행을 샌드박스할 수 있는 V8 가상 머신을 만듭니다.

한 걸음 더 나아가면vm2그것은 굳어진다vmVM에서 신뢰할 수 없는 코드를 실행할 수 있습니다.

  • https://nodejs.org/api/vm.html - 공식 nodejs/vm

  • https://github.com/patriksimek/vm2 - 확장 vm2

const vm = require('vm');

const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

eval()을 사용합니다.

W3 학교 평가 투어.사이트에는 몇 가지 사용 가능한 평가 예가 있습니다.Mozilla 문서에서는 이에 대해 자세히 설명합니다.

이것을 안전하게 사용하는 것에 대해 많은 경고를 받게입니다.이것은 큰 보안상의 문제이므로, 유저가 eval()에 아무것도 삽입하지 않게주세요.

또한 eval()의 스코프가 다르다는 것도 알아야 합니다.

이것을 시험해 보세요.

  var script = "<script type='text/javascript'> content </script>";
  //using jquery next
  $('body').append(script);//incorporates and executes inmediatelly

개인적으로 테스트 안 했는데 잘 되는 것 같아요.

new Function('alert("Hello")')();

이게 제일 좋은 방법인 것 같아요.

@Hossein Hajizadeh alerady가 말한 것과 조금 비슷하지만, 자세한 내용은 다음과 같습니다.

대신할 방법이 있다eval().

함수setTimeout()는 밀리초 간격으로 실행되도록 설계되어 있습니다.실행되는 코드는 문자열로 포맷됩니다.

다음과 같이 동작합니다.

ExecuteJavascriptString(); //Just for running it

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    setTimeout(s, 1);
}

1스트링을 실행하기 전에 1밀리초를 기다립니다.

그것이 가장 올바른 방법은 아닐지 모르지만, 효과가 있다.

복잡하고 난독화된 많은 스크립트에서 이를 체크했습니다.

var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);

아래와 같이 eval을 사용합니다.eval은 신중하게 사용해야 하며, eval is eval에 대한 간단한 검색은 몇 가지 포인터를 던져야 합니다.

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    eval(s);
}

새로운 함수와 apply()도 함께 동작합니다.

var a=new Function('alert(1);')
a.apply(null)

특정 시간 후 특정 명령(문자열)을 실행하려는 경우 - cmd=your code - InterVal=module to run

 function ExecStr(cmd, InterVal) {
    try {
        setTimeout(function () {
            var F = new Function(cmd);
            return (F());
        }, InterVal);
    } catch (e) { }
}
//sample
ExecStr("alert(20)",500);
eval(s);

그러나 사용자가 자신의 브라우저를 크래시 하는 것이 사용자의 문제라고 생각되지만, 사용자로부터 데이터를 빼앗는 경우에는 위험할 수 있습니다.

나는 비슷한 질문에 대답하고 있었고 이것을 어떻게 하면 사용하지 않고 이것을 달성할 수 있는지 또 다른 아이디어를 얻었다.eval():

const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);

위의 코드에서는 기본적으로 오브젝트 URL(브라우저 메모리 내의 파일 또는 블럽 오브젝트의 표현)을 작성하기 위해 스크립트를 포함한 Blob을 작성합니다.srcproperty の 。<script>됩니다.

function executeScript(source) {
    var script = document.createElement("script");
    script.onload = script.onerror = function(){ this.remove(); };
    script.src = "data:text/plain;base64," + btoa(source);
    document.body.appendChild(script);
}

executeScript("alert('Hello, World!');");

이것이 부정행위인지 아닌지 확실하지 않습니다.

window.say = function(a) { alert(a); };

var a = "say('hello')";

var p = /^([^(]*)\('([^']*)'\).*$/;                 // ["say('hello')","say","hello"]

var fn = window[p.exec(a)[1]];                      // get function reference by name

if( typeof(fn) === "function") 
    fn.apply(null, [p.exec(a)[2]]);                 // call it with params

스테판의 답변 연장:

//Executes immediately
function stringToFunctionAndExecute(str) {
    let func = new Function(str);
    return (func()); // <--- note the parenteces
}

//Executes when called
function stringToFunctionOnly(str) {
    let func = new Function(str);
    return func;
}

// -^-^-^- Functions -^-^-^- (feel free to copy)
// -v-v-v- Explanations -v-v-v- (run code to read easier)

console.log('STEP 1, this executes directly when run:')
let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')");

console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:")
try {
  func_A();    
} catch (error) {
  console.log('STEP ERROR, see, it failed', error)    
}

console.log('STEP 3, but this will NOT execute directly AND you can save it for later...')
let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')");

console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:")
func_B();

console.log('STEP 5, TADAAAAA!!')

eval이 할 수 있어요.

eval(s);

mathjs를 사용할 수 있습니다.

위 링크의 스니펫:

// evaluate expressions
math.evaluate('sqrt(3^2 + 4^2)')        // 5
math.evaluate('sqrt(-4)')               // 2i
math.evaluate('2 inch to cm')           // 5.08 cm
math.evaluate('cos(45 deg)')            // 0.7071067811865476

// provide a scope
let scope = {
    a: 3,
    b: 4
}
math.evaluate('a * b', scope)           // 12
math.evaluate('c = 2.3 + 4.5', scope)   // 6.8
scope.c                                

scope는 임의의 오브젝트입니다.따라서 글로벌 스코프를 eval 함수에 전달하면 alert()를 동적으로 실행할 수 있습니다.

또한 mathjs는 샌드박스에서 실행되므로 eval()보다 훨씬 좋은 옵션입니다.

사용자가 표현식 파서를 통해 악의적인 JavaScript 코드를 주입하려고 시도할 수 있습니다.mathjs의 식 파서는 식을 실행할 수 있는 샌드박스 환경을 제공하며, 이는 불가능해야 합니다.알 수 없는 보안 취약성이 있을 수 있으므로 특히 서버 측에서 임의 식을 실행할 수 있도록 허용하는 경우 주의해야 합니다.

새로운 버전의 mathjs에서는 eval() 또는 Function()은 사용되지 않습니다.

파서는 보안 공격의 주요 원인인 JavaScripts 내부 평가 및 새로운 기능에 대한 접근을 적극적으로 방지합니다.Mathjs 버전 4 이후는 후드에서 JavaScript의 평가를 사용하지 않습니다.버전 3 이전 버전에서는 컴파일 스텝에 eval이 사용되었습니다.이는 직접적인 보안 문제는 아니지만 더 큰 공격 표면으로 이어질 수 있습니다.

eval(s);

하지만 그 평가는 매우 강력하고 안전하지 않다는 것을 기억하라.실행 중인 스크립트가 사용자가 안전하고 변경할 수 없음을 확인해야 합니다.

javascript를 실행하기 위해 eval을 사용하는 것과 새로운 함수를 만드는 것은 많은 보안 위험을 수반합니다.

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

스트링으로 받은 Javascript를 실행할 때는 이 방법을 선호합니다.

언급URL : https://stackoverflow.com/questions/939326/execute-javascript-code-stored-as-a-string

반응형