How to solve concurrency problems when trying to p

2019-08-11 20:00发布

问题:

I am trying to use PhantomJS to loop through a couple of URLs, open the pages and check if there was an alert on any of the pages. I am also printing the URLs of the pages where an alert occurred.

The code is as below:

var page = require('webpage');

var u = ["http://127.0.0.1/DVWA-1.0.8/vulnerabilities/xss_r/?name=<SCRIPT>alert('XSS');</SCRIPT>", "http://127.0.0.1/DVWA-1.0.8/vulnerabilities/xss_r/?name=abcd"]
var url = "";

for(var i = 0; i < u.length; i++) {
  url = u[i];

  var webpage = page.create();

  phantom.addCookie({
    'name':'PHPSESSID',
    'value':'00885b45d9ddda3e757371b177c5959b',
    'domain':'127.0.0.1'
  });

  webpage.onAlert = function(alertMessage){
    console.log("Alert URL: " + webpage.url);
    console.log("Alert occured with message: " + alertMessage);
  }

  webpage.open(url, function (status) {
    console.log("Opening URL:  " + webpage.url);
    phantom.exit();
  });
}

I would expect the part of the output to be:

Alert URL: http://127.0.0.1/DVWA-1.0.8/vulnerabilities/xss_r/?name=<SCRIPT>alert('XSS');</SCRIPT>
Alert occured with message: XSS

But instead, it differs each time and shows incorrect output like:

Alert URL: http://127.0.0.1/DVWA-1.0.8/vulnerabilities/xss_r/?name=abcd
Alert occured with message: XSS

It looks like this happens because of the concurrency of the callbacks.

Is there a way to handle this in order to ensure that the output is as expected? Or is this library not meant to be used like this and should I try something else?

回答1:

You create a new page in the loop which is essentially a new tab as far as the PhantomJS runtime is concerned. It will be executed concurrently. To add structure and reproducability to the script, you would have to write a little chaining.

Something like this should work:

var page = require('webpage');

var u = ["http://127.0.0.1/DVWA-1.0.8/vulnerabilities/xss_r/?name=<SCRIPT>alert('XSS');</SCRIPT>", "http://127.0.0.1/DVWA-1.0.8/vulnerabilities/xss_r/?name=abcd"]

function each(list, func, done){
  var len = list.length,
      previous = done;
  for(var i = len - 1; i >= 0; i--) {
    (function(item, done){ // IIFE
      previous = function(){
        func(item, done);
      };
    })(list[i], previous);
  }
  previous(); // start the chain
}

each(u, function(url, done){
  var webpage = page.create();

  phantom.addCookie({
    'name':'PHPSESSID',
    'value':'00885b45d9ddda3e757371b177c5959b',
    'domain':'127.0.0.1'
  });

  webpage.onAlert = function(alertMessage){
    console.log("Alert URL: " + webpage.url);
    console.log("Alert occured with message: " + alertMessage);
  }

  webpage.open(url, function (status) {
    console.log("Opening URL:  " + webpage.url);
    done();
  });
}, function(){
  phantom.exit();
});