Search code examples
javascriptpythonpython-2.7urljavascript-injection

Javascript Injection with PYthon


I am attempting to use python to open up web pages, and the perform a javascript injection. The goal is to actually change the values of some forms (ex: putting data into a form) Currently the test program that I have written for opening up a page is:

import urllib2 as u
f = u.urlopen("http://www.google.com")
print f.read()
f.close()

So now what I was thinking for the injection (in this case printing Hello world)

import urllib2 as u
f = u.urlopen("http://www.google.com/javascript:alert(\" hello world \")")
print f.read()
f.close()

But when I run the code I recieve the following error:

Traceback (most recent call last):
  File "c:\Sid\Rutgers\3 Semester\HackHerz\ChalupaCity\Sid\thefile.py", line 12, in <module>
    f = u.urlopen("http://www.google.com/javascript:alert(\" hello world \")")
  File "c:\Anaconda\lib\urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "c:\Anaconda\lib\urllib2.py", line 410, in open response = meth(req, response)
  File "c:\Anaconda\lib\urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "c:\Anaconda\lib\urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "c:\Anaconda\lib\urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "c:\Anaconda\lib\urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: Bad Request

So i decided to explore a bit. And I discovered that python is probably going to the URL of the name

http://www.google.com/javascript:alert(\" hello world \")

So I tried to separate into two lines

f = u.urlopen("http://www.google.com/")

f.urlopen("javascript:alert(\" hello world \")")
print f.read()
f.close()

But that doesn't work either.

How to go through with this? Ultimately I want to be able to change form data with Javascript.


Solution

  • Possibly using Beautiful Soup?

    You may also wish to look into urllib2 module or requests library to assist you.

    Or you could try updating the HTTP headers with the desired post data before you reply to the server.

    Good luck!