it-source

Facebook은 브라우저의 통합 개발자 도구를 어떻게 비활성화합니까?

criticalcode 2022. 10. 21. 22:42
반응형

Facebook은 브라우저의 통합 개발자 도구를 어떻게 비활성화합니까?

최근의 사기 때문에 개발자 툴은 스팸을 투고하기 위해 이용되고 있으며, 계정 해킹에도 사용되고 있습니다.페이스북이 개발자 도구를 차단해서 콘솔도 사용할 수 없어요.

여기에 이미지 설명을 입력하십시오.

어떻게 한 거지?한 Stack Overflow 게시물은 불가능하다고 주장했지만 페이스북은 그들이 틀렸다는 것을 증명했다.

Facebook에 접속하여 개발자 툴을 열고 콘솔에 1개의 문자를 입력하면 이 경고가 나타납니다.무엇을 넣어도 실행되지 않습니다.

이것이 어떻게 가능한 걸까요?

또한 콘솔에서 자동 완료를 차단했습니다.

여기에 이미지 설명을 입력하십시오.

나는 페이스북 보안 엔지니어이고 이건 내 잘못이야.일부 사용자를 대상으로 테스트하여 사용자가 브라우저 콘솔에 JavaScript 코드를 붙여 넣는(악의가 있는) 공격을 줄일 수 있는지 확인합니다.

참고로 해커의 클라이언트 측을 차단하는 것은 일반적으로 좋지 않습니다.이는 특정 사회공학적 공격으로부터 보호하기 위한 것입니다.

만약 당신이 테스트 그룹에 속하게 되어 이것에 짜증이 난다면, 죄송합니다.오래된 옵트아웃 페이지(현재의 도움말 페이지)를 가능한 한 심플하게 만들려고 노력했지만, 그래도 일부 희생자를 막을 수 있을 만큼 충분히 무서웠습니다.

실제 코드는 @joeldixon66의 링크와 매우 유사합니다.우리 코드는 정당한 이유 없이 조금 복잡합니다.

Chrome은 모든 콘솔 코드를 감싼다.

with ((console && console._commandLineAPI) || {}) {
  <code goes here>
}

이 정의한다...이 、 이 、 이는console._commandLineAPI★★★★★★★★★★★★★★★★★★:

Object.defineProperty(console, '_commandLineAPI',
   { get : function() { throw 'Nooo!' } })

이 정도로는 부족하지만(해 보세요!) 그것이 주된 요령입니다.


에필로그:Chrome 팀은 사용자 측 JS에서 콘솔을 파괴하는 것은 버그라고 판단하고 문제를 수정하여 이 기술을 무효화했습니다.그 후 사용자를 셀프 xss로부터 보호하기 위해 보호가 추가되었습니다.

Chrome 개발자 툴을 사용하여 Facebook의 콘솔버스터 스크립트를 찾았습니다.다음은 읽기 쉽도록 약간 변경된 스크립트입니다.이해할 수 없는 부분을 삭제했습니다.

Object.defineProperty(window, "console", {
    value: console,
    writable: false,
    configurable: false
});

var i = 0;
function showWarningAndThrow() {
    if (!i) {
        setTimeout(function () {
            console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
        }, 1);
        i = 1;
    }
    throw "Console is disabled";
}

var l, n = {
        set: function (o) {
            l = o;
        },
        get: function () {
            showWarningAndThrow();
            return l;
        }
    };
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);

이렇게 하면 콘솔 자동 완성은 자동으로 실패하고 콘솔에 입력된 문은 실행되지 않습니다(예외가 기록됩니다).

참고 자료:

어떤 페이지에서도 그걸 촉발시킬 수 없었어요보다 견고한 버전이라면 다음과 같이 할 수 있습니다.

window.console.log = function(){
    console.error('The developer console is temp...');
    window.console.log = function() {
        return false;
    }
}

console.log('test');

출력을 스타일링하려면:JavaScript 콘솔의 색상

Edit Thinking @joeldixon66은 올바른 아이디어입니다.콘솔 : ::: Kspace ::: 에서 JavaScript 실행을 비활성화합니다.

★★★★★★★★★★★★★★★★를 재정의하는 것 외에console._commandLineAPIWebKit 브라우저에서 InjectedScriptHost에 침입하여 개발자 콘솔에 입력된 표현식의 평가를 방지하거나 변경하는 다른 방법이 있습니다.

편집:

크롬은 이전 릴리스에서 이를 수정했습니다.- 2015년 2월 이전이어야 합니다.그때의 요지는 제가 작성했습니다.

그래서 여기 다른 가능성이 있습니다.에는 한 접속합니다.InjectedScriptInjectedScriptHost이전 버전과 달리.

은 patch를 할 수 때문에 InjectedScript._evaluateAndWrapInjectedScriptHost.evaluate그래야 무슨 일이 일어나는지 보다 세밀하게 제어할 수 있기 때문입니다.

또 다른 매우 흥미로운 점은 식을 평가할 때 내부 결과를 가로채 일반 동작 대신 사용자에게 반환할 수 있다는 것입니다.

다음 코드는 정확히 이를 위해 사용자가 콘솔에서 무언가를 평가할 때 내부 결과를 반환합니다.

var is;
Object.defineProperty(Object.prototype,"_lastResult",{
   get:function(){
       return this._lR;
   },
   set:function(v){
       if (typeof this._commandLineAPIImpl=="object") is=this;
       this._lR=v;
   }
});
setTimeout(function(){
   var ev=is._evaluateAndWrap;
   is._evaluateAndWrap=function(){
       var res=ev.apply(is,arguments);
       console.log();
       if (arguments[2]==="completion") {
           //This is the path you end up when a user types in the console and autocompletion get's evaluated

           //Chrome expects a wrapped result to be returned from evaluateAndWrap.
           //You can use `ev` to generate an object yourself.
           //In case of the autocompletion chrome exptects an wrapped object with the properties that can be autocompleted. e.g.;
           //{iGetAutoCompleted: true}
           //You would then go and return that object wrapped, like
           //return ev.call (is, '', '({test:true})', 'completion', true, false, true);
           //Would make `test` pop up for every autocompletion.
           //Note that syntax as well as every Object.prototype property get's added to that list later,
           //so you won't be able to exclude things like `while` from the autocompletion list,
           //unless you wou'd find a way to rewrite the getCompletions function.
           //
           return res; //Return the autocompletion result. If you want to break that, return nothing or an empty object
       } else {
           //This is the path where you end up when a user actually presses enter to evaluate an expression.
           //In order to return anything as normal evaluation output, you have to return a wrapped object.

           //In this case, we want to return the generated remote object. 
           //Since this is already a wrapped object it would be converted if we directly return it. Hence,
           //`return result` would actually replicate the very normal behaviour as the result is converted.
           //to output what's actually in the remote object, we have to stringify it and `evaluateAndWrap` that object again.`
           //This is quite interesting;
           return ev.call (is, null, '(' + JSON.stringify (res) + ')', "console", true, false, true)
       }
   };
},0);

좀 장황하긴 한데 제가 댓글을 달았나 봐요.

보통 를 들어 ""를 평가했을 ,[1,2,3,4]하다

여기에 이미지 설명 입력

InjectedScript._evaluateAndWrap과 같은이 나옵니다.

여기에 이미지 설명 입력

왼쪽 작은 화살표는 출력을 나타냅니다만, 이번에는 오브젝트가 표시됩니다..[1,2,3,4]는 모든 속성을 포함하는 개체로 표시됩니다.

에러를 발생시키는 표현도 포함해 이것저것 평가하는 것을 추천합니다.꽤 흥미롭습니다.

이 때 ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ)도is - - 오브젝트여기에는 인스펙터의 내부를 파악하고 조작할 수 있는 몇 가지 방법이 있습니다.

물론 모든 정보를 가로채고 원래 결과를 사용자에게 반환할 수 있습니다.

그냥 그 밖의 다른 경로에서다른경로의 반환 스테이트먼트를에 의해 반환 성명서 교체한다.console.log (res)한에 이어 다음return res. 그럼 너를 다음으로 안 되잖아요그러면 다음과 같은결과가 됩니다.

여기에 이미지 설명 입력

편집 종료


이것은 구글이 수정한 이전 버전입니다.따라서 더 이상 불가능한 방법이 아닙니다.

하나의그중 하나가에끼여들고 있다 에 연결한다.Function.prototype.call

크롬 Chrome은 입력된식을다음과 같이 평가합니다에 의해 입력한 표현을 측정한다.call잉 감독은 eavl함수 그평가 기능을 주입하다.InjectedScriptHost~하듯이로thisArg

var result = evalFunction.call(object, expression);

이런 점을 고려하면, 당신은이 점으로 볼 때론을 들을 수 있다.thisArg의의call존재는 것evaluate그리고 첫번째 인수에 대한 참조(첫 번째 인수에 대한 참조를 얻습니다(.InjectedScriptHost))

if (window.URL) {
    var ish, _call = Function.prototype.call;
    Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
        if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
            ish = arguments[0];
            ish.evaluate = function (e) { //Redefine the evaluation behaviour
                throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
            };
            Function.prototype.call = _call; //Reset the Function.prototype.call
            return _call.apply(this, arguments);  
        }
    };
}

예를 들어 평가가 거부된 오류를 발생시킬 수 있습니다.

여기에 이미지 설명 입력

다음으로 입력된 식을 CoffeeScript 컴파일러에 전달하기 전에 CoffeeScript 컴파일러에 전달하는 예를 나타냅니다.evaluate기능.★★★★★★ 。

넷플릭스도 이 기능을 구현합니다.

(function() {
    try {
        var $_console$$ = console;
        Object.defineProperty(window, "console", {
            get: function() {
                if ($_console$$._commandLineAPI)
                    throw "Sorry, for security reasons, the script console is deactivated on netflix.com";
                return $_console$$
            },
            set: function($val$$) {
                $_console$$ = $val$$
            }
        })
    } catch ($ignore$$) {
    }
})();

'무조건'을 덮어쓸 뿐이다.console._commandLineAPI이치노

이것은 페이스북이 가능했기 때문에 실제로 가능하다.실제 웹 개발자 도구가 아니라 콘솔에서 Javascript를 실행하는 것입니다.

다음을 참조하십시오.Facebook은 브라우저의 통합 개발자 도구를 어떻게 비활성화합니까?

이러한 유형의 클라이언트 측 보안을 우회하는 다른 방법이 있기 때문에 이 방법은 많은 도움이 되지 않습니다.

클라이언트측이라고 하면, 서버의 제어 밖에 있기 때문에, 할 수 있는 일은 별로 없습니다.Facebook이 아직도 이것을 하는 이유를 묻는다면, 이것은 보안을 위해서가 아니라 javascript를 모르는 일반 사용자가 콘솔에서 코드를 실행하는 것(읽을 줄 모르는 것)을 보호하기 위해서이다.이것은 오토리커 서비스나 페이스북 기능 봇을 약속하는 사이트에서 흔히 볼 수 있는 현상입니다.대부분의 경우 콘솔에서 실행할 수 있는 Javascript를 제공합니다.

Facebook만큼 사용자가 많지 않다면 Facebook이 하고 있는 일을 할 필요가 없다고 생각합니다.

콘솔에서 Javascript를 비활성화해도 주소 표시줄을 통해 Javascript를 실행할 수 있습니다.

여기에 이미지 설명 입력

여기에 이미지 설명 입력

브라우저가 주소바에서 javascript를 비활성화할 경우(Google Chrome에서 주소바에 코드를 붙여넣으면 'javascript:'라는 문구를 삭제하여 검사 요소를 통해 링크 중 하나에 javascript를 붙여넣을 수 있습니다).

앵커 검사:

여기에 이미지 설명 입력

href에 코드 붙여넣기:

여기에 이미지 설명 입력

여기에 이미지 설명 입력

여기에 이미지 설명 입력

결론은 서버측의 검증이며, 시큐러티를 우선으로 하고, 다음에 클라이언트측의 검증을 실시합니다.

Facebook이 콘솔을 사용할 수 없게 된 이후로 크롬이 많이 바뀌었습니다.

2017년 3월부로 이것은 더 이상 작동하지 않습니다.

콘솔 기능의 일부를 디세블로 하는 것이 최선입니다.다음은 예를 제시하겠습니다.

if(!window.console) window.console = {};
var methods = ["log", "debug", "warn", "info", "dir", "dirxml", "trace", "profile"];
for(var i=0;i<methods.length;i++){
    console[methods[i]] = function(){};
}

내 간단한 방법이지만, 이 주제에 대해 더 많은 변화를 줄 수 있어.모든 방법을 나열하고 쓸모없는 방법으로 변경합니다.

  Object.getOwnPropertyNames(console).filter(function(property) {
     return typeof console[property] == 'function';
  }).forEach(function (verb) {
     console[verb] =function(){return 'Sorry, for security reasons...';};
  });

단, 개발자 도구를 의미 있는 방법으로 열지 않도록 하는 것이 좋습니다.

(function() {
    'use strict';
    Object.getOwnPropertyNames(console).filter(function(property) {
        return typeof console[property] == 'function';
    }).forEach(function (verb) {
        console[verb] =function(){return 'Sorry, for security reasons...';};
    });
    window.addEventListener('devtools-opened', ()=>{
        // do some extra code if needed or ...
        // maybe even delete the page, I still like to add redirect just in case
        window.location.href+="#";
        window.document.head.innerHTML="";
        window.document.body.innerHTML="devtools, page is now cleared";
    });
    window.addEventListener('devtools-closed', ()=>{
        // do some extra code if needed
    });
    let verifyConsole = () => {
        var before = new Date().getTime();
        debugger;
        var after = new Date().getTime();
        if (after - before > 100) { // user had to resume the script manually via opened dev tools 
            window.dispatchEvent(new Event('devtools-opened'));
        }else{
            window.dispatchEvent(new Event('devtools-closed'));
        }
        setTimeout(verifyConsole, 100);
    }
    verifyConsole();        
})();

내부 devtools는 IIFE를 주입합니다.getCompletionsDevtools 콘솔 내에서 키를 누르면 호출되는 페이지로 이동합니다.

함수의 소스를 보면 덮어쓸 수 있는 몇 가지 글로벌 함수를 사용합니다.

컨스트럭터를 사용하면 다음과 같은 콜스택을 얻을 수 있습니다.getCompletionsDevtools에 의해 호출됩니다.


예:

const disableDevtools = callback => {
  const original = Object.getPrototypeOf;

  Object.getPrototypeOf = (...args) => {
    if (Error().stack.includes("getCompletions")) callback();
    return original(...args);
  };
};

disableDevtools(() => {
  console.error("devtools has been disabled");

  while (1);
});

간단한 해결책!

setInterval(()=>console.clear(),1500);

여기 간단한 방법이 있습니다.window.console = function () {}

나는 다음과 같은 방법을 택할 것이다.

Object.defineProperty(window, 'console', {
  get: function() {

  },
  set: function() {

  }
});

Firefox에서는 그렇지 않습니다. Firefox는 개발자 브라우저이기 때문에 명령어 이후부터WEBGL_debug_renderer_info is deprecated in Firefox and will be removed. Please use RENDERER및 오류Referrer Policy: Less restricted policies, including ‘no-referrer-when-downgrade’, ‘origin-when-cross-origin’ and ‘unsafe-url’, will be ignored soon for the cross-site request: https://static.xx.fbcdn.net/rsrc.php/v3/yS/r/XDDAHSZfaR6.js?_nc_x=Ij3Wp8lg5Kz.

이는 취약한 코드를 방치하기 위한 보안 조치가 아닙니다.이 전략을 구현하기 전에 항상 취약한 코드를 영구적으로 해결하고 웹 사이트를 적절히 보호하십시오.

제가 아는 한 최고의 도구는 콘텐츠를 새로 고치거나 교체함으로써 페이지의 무결성을 단순히 정상으로 되돌리는 여러 javascript 파일을 추가하는 것입니다.코드는 브라우저의 일부이며 서버 렌더링이 아니기 때문에 이 개발자 도구를 비활성화하는 것이 가장 좋은 방법은 아닙니다.따라서 코드가 깨질 수 있기 때문에 바이패스는 항상 문제가 있습니다.

그랬어야 했는데js file one확인중<element>중요한 요소의 변경 및js file two그리고.js file three이 파일이 기간별로 존재하는지 확인하면 기간 내 페이지에서 완전한 무결성을 복원할 수 있습니다.

4개의 파일의 예를 들어 무슨 뜻인지 보여 드리겠습니다.

index.displaces를 표시합니다.

   <!DOCTYPE html>
   <html>
   <head id="mainhead">
   <script src="ks.js" id="ksjs"></script>
   <script src="mainfile.js" id="mainjs"></script>
   <link rel="stylesheet" href="style.css" id="style">
   <meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
   </head>
   <body>
   <h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
   <h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>

   <p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it. 
   </p>

   <p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
   </body>
   <script src="ps.js" id="psjs"></script>
   </html>

mainfile.mainfile.displaces

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var ksExists = document.getElementById("ksjs"); 
   if(ksExists) {
   }else{ location.reload();};

   var psExists = document.getElementById("psjs");
   if(psExists) {
   }else{ location.reload();};

   var styleExists = document.getElementById("style");
   if(styleExists) {
   }else{ location.reload();};


   }, 1 * 1000); // 1 * 1000 milsec

ps.displaces(온보드)

   /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.

   */

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var mainExists = document.getElementById("mainjs"); 
   if(mainExists) {
   }else{ location.reload();};

   //check that heading with id exists and name tag is dontdel.
   var headingExists = document.getElementById("heading"); 
   if(headingExists) {
   }else{ location.reload();};
   var integrityHeading = headingExists.getAttribute('name');
   if(integrityHeading == 'dontdel') {
   }else{ location.reload();};
   var integrity2Heading = headingExists.getAttribute('value');
   if(integrity2Heading == '2') {
   }else{ location.reload();};
   //check that all meta tags stay there
   var meta1Exists = document.getElementById("meta1"); 
   if(meta1Exists) {
   }else{ location.reload();};

   var headExists = document.getElementById("mainhead"); 
   if(headExists) {
   }else{ location.reload();};

   }, 1 * 1000); // 1 * 1000 milsec

ks.120

   /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.

   */

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var mainExists = document.getElementById("mainjs"); 
   if(mainExists) {
   }else{ location.reload();};
   //Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
   var x = document.getElementsByTagName("meta")[0];
   var p = x.getAttribute("name");
   var s = x.getAttribute("content");
   if (p != 'description') {
   location.reload();
   }
   if ( s != 'Proper mitigation against script kiddies via Javascript') {
   location.reload();
   }
   // This will prevent a meta tag after this meta tag @ id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
   var lastMeta = document.getElementsByTagName("meta")[1];
   if (lastMeta) {
   location.reload();
   }
   }, 1 * 1000); // 1 * 1000 milsec

style.css

이것은, 모든 파일이나 태그에서도 동작하고 있는 것을 나타내고 있습니다.

   #heading {
   background-color:red;
   }

이 모든 파일을 정리해 예를 작성하면 이 측정의 기능을 알 수 있습니다.이는 특히 PHP를 사용할 때 인덱스 파일의 모든 중요한 요소에 올바르게 구현해야 하는 예기치 않은 주입을 방지할 수 있습니다.

속성별 정상값으로 되돌리는 대신 새로고침을 선택한 이유는 일부 공격자가 웹 사이트의 다른 부분을 이미 구성하고 준비하여 코드 양을 줄일 수 있기 때문입니다.새로고침으로 공격자의 모든 힘든 작업이 제거되고 공격자는 아마도 더 쉬운 곳으로 놀러 갈 것입니다.

다른 주의사항:이것은 많은 코드가 될 수 있기 때문에 깨끗하게 유지하고 나중에 쉽게 편집할 수 있도록 정의를 추가해야 합니다. 또, 1초 간격으로 큰 페이지를 표시하면, 방문자가 사용하고 있는 낡은 컴퓨터에 큰 영향을 줄 가능성이 있기 때문에, 원하는 초수를 설정합니다.

언급URL : https://stackoverflow.com/questions/21692646/how-does-facebook-disable-the-browsers-integrated-developer-tools

반응형