Challenge the routine -- why shouldn't Jsonp be used for cross domain

General cross domain approach

Common cross domain methods include:

  1. Add access control allow origin
  2. Background server agent
  3. Jsonp

1. 2. Both methods are safe and reliable. 3. They are not safe and reliable

The essence of Json

The essence of Json is to reference and execute external JavaScript script. The principle is that the < script > tag is not limited by the domain name, and the js function is executed by dynamically creating < script >

Use of Jsonp

jQuery performs Jsonp usage

$.ajax(url,{
        dataType:"jsonp",
        error:function(jqXHR,textStatus,errorThrown)
        {
            //TODO
        },
        success:function(data)
        {
            //TODO
        }
    });

JQuery 3.3.1 load and execute external js

function DOMEval( code, doc, node ) {
    doc = doc || document;

    var i,
        script = doc.createElement( "script" );

    script.text = code;
    if ( node ) {
        for ( i in preservedScriptAttributes ) {
            if ( node[ i ] ) {
                script[ i ] = node[ i ];
            }
        }
    }
    doc.head.appendChild( script ).parentNode.removeChild( script );
}

Unsafe

User input is untrusted, as is external scripts. If site A refers to the cross domain script of site B, the security of site A is restricted by site B.

In the case of security, safeapi.php

<?php
date_default_timezone_set('asia/shanghai');
$result=json_encode(array("msg"=>"Hello,current time:".date("Y-m-d H:i:s e")));
if(isset($_REQUEST['callback']))
{
    header("Content-Type:text/javascript;charset=utf-8"); 
    echo $_REQUEST['callback']."(".$result.")";
}else
{
    header("Content-Type:application/json;charset=utf-8");
    echo $result;
}

B site is under attack or malicious code, danger.php

<?php
header("Content-Type:text/javascript;charset=utf-8"); 
if(isset($_REQUEST['callback']))
{ 
    echo $_REQUEST['callback']."("; 
}else
{
    echo "_(";  
}
echo json_encode(array("msg"=>"Hello,current time:".date("Y-m-d H:i:s")));
echo ");console.log('do something');";

Output do something from the console under website A

Reflection

We should isolate the security of the website and do not trust the external script easily, otherwise it is easy to cause security risks such as account leakage. If you really need to reference and execute external scripts, you can use CSP policy instructions for whitelist control, such as:

Content-Security-Policy: default-src 'self' trustedscripts.foo.com

Keywords: Javascript PHP JSON JQuery

Added by txhoyt on Thu, 12 Dec 2019 21:37:27 +0200