Regex and POST in same connection - regex

please bear with me, i'm brand new to Python!
I'm trying to login to a website which uses PHP. The form contains two hidden fields, the value of one and the name of another are generated on page load.
My code below successfuly accesses the page and using regex manages to return the values - great!
The problem I am having is that I then generate my querystring that will be used for the POST (this contains the two values obtained earlier) and opens the url again. This generates brand new tokens/values and my originals are of no use.
Can someone shed some light on how I can connect to a site, use regex to get the values and then POST all in the same connection.
I hope i've made myself clear, if not please let me know.
Thanks in advance for your help.
import urllib2,urllib,re,cookielib
url='http://www.example.com/index.php'
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
response = urllib2.urlopen(req)
link=response.read()
response.close()
token1=re.compile('<input type="hidden" name="return" value="(.+?)" />').findall(link)
token2=re.compile('<input type="hidden" name="(.+?)" value="1" />').findall(link)
print token1[0]
print token2[0]
username = 'username'
password = 'password'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'password' : password, 'return' : token1[0], token2[0] : '1', 'Submit' : 'Log in', 'option' : 'com_users', 'task' : 'user.login'})
opener.open('http://www.example.com/index.php', login_data)
resp = opener.open('http://www.example.com/index.php')
FORM:
<form action="/index.php/welcome2" method="post" id="login-form" >
<fieldset class="userdata">
<p id="form-login-username">
<label for="modlgn-username">User Name</label>
<input id="modlgn-username" type="text" name="username" class="inputbox" size="18" />
</p>
<p id="form-login-password">
<label for="modlgn-passwd">Password</label>
<input id="modlgn-passwd" type="password" name="password" class="inputbox" size="18" />
</p>
<p id="form-login-remember">
<label for="modlgn-remember">Remember Me</label>
<input id="modlgn-remember" type="checkbox" name="remember" class="inputbox" value="yes"/>
</p>
<input type="submit" name="Submit" class="button" value="Log in" />
<input type="hidden" name="option" value="com_users" />
<input type="hidden" name="task" value="user.login" />
<input type="hidden" name="return" value="aW5kZXgucGhwP0l0ZW1pZD0xMjc=" />
<input type="hidden" name="c813c34837e4e48e8e3268c0a42912a2" value="1" />
</fieldset>
<ul>
<li>
<a href="/index.php/my-account/my-details?view=reset">
Forgot your password?</a>
</li>
<li>
<a href="/index.php/my-account/my-details?view=remind">
Forgot your username?</a>
</li>
<li>
<a href="/index.php/register">
Create an account</a>
</li>
</ul>
</form>

When you write...
opener.open('http://www.example.com/index.php', login_data)
resp = opener.open('http://www.example.com/index.php')
Why not just this?
resp = opener.open('http://www.example.com/index.php', login_data)
I've never used this Python library, but my first reaction is that this would give you the response text all in one request, with which you can get the new token, wouldn't it?
Update based on form: It looks like your problem is you're POSTing the login info to index.php rather than index.php/welcome.

Related

brute force simple authentication

Hi to all I am new to python intermediate level and I am trying to develop simple authentication brute force tool, I am really unaware where I missed please someone correct my mistake I am trying this code in mutillidea and bwapp. code is listed below
!/usr/bin/python
import mechanize
import itertools
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
combos = itertools.permutations("pwa",3)
r = br.open("http://127.0.0.1/bwapp/login.php")
for x in combos:
new_form = '''
<<form action="/bwapp/login.php" method="POST">
<p><label for="login">Login:</label><br />
<input type="text" id="login" name="login" size="20" autocomplete="off"></p>
<p><label for="password">Password:</label><br />
<input type="password" id="password" name="password" size="20" autocomplete="off"></p>
<p><label for="security_level">Set the security level:</label><br />
<select name="security_level">
<option value="0">low</option>
<option value="1">medium</option>
<option value="2">high</option>
</select>
</p>
<button type="submit" name="form" value="submit">Login</button>
</form>
'''
r.set_data(new_form)
br.set_response(r)
br.select_form( nr = 0 )
br.form['login'] = 'bee'
br.form['password'] = ''.join(x)
br.form['security_level'] = 0
print "Checking ",br.form['password']
response=br.submit()
if response.geturl()=="http://127.0.0.1/bwapp/portal.php":
#url to which the page is redirected after login
print "Correct password is ",''.join(x)
break
Error I am getting is I cannot get correct password

Use form information in external POST request

I've built a simple form to open up a JIRA ticket based on user input. I've almost got all of it, except I don't know how to use the form element in the POST request. Here's what I have so far:
<form target="_blank" action='http://baseurl.com/secure/CreateIssueDetails!init.jspa?pid=10517&issuetype=3&summary=Change+application+name+to+{{new_name}}&reporter={{request.user}}&priority=5&assignee=xxx' method='post'>
<label for="new_name">New name: </label>
<input id="new_name" type="text" name="new_name" value="{{item.name}}">
<input type="submit" value="Create JIRA ticket">
</form>
So I just need the value the user puts in the new_name element to be passed into the appropriate spot in the URL. How do I access that?
It sounds like you're getting POST and GET mixed. POST data would not be included in the URL itself, but rather in the request payload itself.
So, your URL would be http://baseurl.com/secure/CreateIssueDetails!init.jspa
The payload would be separately put in the body of the HTTP request.
If you need to use a GET method, the URL itself would be the same as above, but the URL that eventually gets hit would be http://baseurl.com/secure/CreateIssueDetails!init.jspa?new_name=WHATEVERVALUE.
If you need additional key-value pairs to get passed, just add them as hidden fields and pass them that way.
Your code, edited:
<form target="_blank" action='http://baseurl.com/secure/CreateIssueDetails!init.jspa' method='post'> <!-- ARE YOU SURE IT'S A POST REQUEST AND NOT A GET? -->
<label for="new_name">New name: </label>
<input id="new_name" type="text" name="new_name" value="{{item.name}}">
<input type="hidden" value="10517" name="pid">
<input type="hidden" value="3" name="issuetype">
<input type="hidden" value="5" name="priority">
<input type="hidden" value="Change application name to {{new_name}}" name="summary">
<input type="hidden" value="{{request.user}}" name="reporter">
<input type="hidden" value="xxx" name="assignee">
<input type="submit" value="Create JIRA ticket">
</form>
Makes sense?

How can I access data sent in a post request in Django?

I have a form that is supposed to create a new 'Quote' record in Django. A 'Quote' requires a BookID for a foreign key.
This is my form
<form method="POST" action="{% url 'quotes:createQuote' %}">
{% csrf_token %}
<section>
<label for="q_text">Quote Text</label>
<input type="text" name="text" id="q_text" placeholder="Enter a Quote" style="padding-left:3px"> <br>
<label for="q_book">Book ID</label>
<input type="text" name="bookID" id="q_book" placeholder="Enter Book ID" style="padding-left:3px"> <br>
<label for="q_disp">Display Quote Now?</label>
<input type="radio" name="display" id="q_disp" value="True"> True
<input type="radio" name="display" value ="False">False <br>
<button value="submit">Submit</button>
</section>
</form>
And this is the method that it is targeting
def createQuote(request):
#b = get_object_or_404(Book, pk=request.bookID)
return HttpResponseRedirect(reverse('quotes:index'))
Somewhere in that request argument I assume there is some sort of field that contains the bookID the user will pass in on the form. How do I get at that information?
Bonus points for anyone who can tell me some way I can visualise data like I might with console.log(some.collection) in Javascript
if request.method == "POST":
book_id = request.POST['book_id']
Assuming you're sure it's in there. Otherwise you'll need to verify/provide a default value like you would for a normal python dictionary.
As for visualising the data, do you mean printing it to the console? In which case if you're running the django runserver you can just do print some_data. If you want it formatted a little nicer, you can use pretty print:
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(some_data)

How to make Chrome respect the names of my fields and not attempt to autocomplete

I have two different forms on my home page: one for logins and one for registrations. As you can see from the code, the forms have inputs with different names:
<h3> Log In </h3>
<form action="/login/" method="POST" class="form-vertical" style="padding-top: 5px">
<input id="id_login_username" type="text" name="login_username" maxlength="25" />
<input type="password" name="login_password" id="id_login_password" /><br>
<button type="submit" class="btn btn-info">Login</button>
</form>
<h3> Sign Up <small>(It's free!)</small></h3>
<form action="/register/" method="POST" class="form-vertical" style="padding-top: 5px">
<input id="id_register_username" type="text" name="register_username" maxlength="25" />
<input type="text" name="register_email" id="id_register_email" />
<input type="password" name="register_password" id="id_register_password" />
<input type="password" name="register_password2" id="id_register_password2" /><br>
<button type="submit" class="btn">Submit</button>
</form>
Which renders to this in Chrome:
What can be causing this? And how can I fix it?
That's a really good question and I'm sorry to say I have no idea. Did
you try to register once and also login at least once? If so, that
"might" be what's causing it as browsers come complete with the
"autoremember" feature.
Assuming autofill is enabled (it is by default), the reason it autofills the rest is because chrome's autofill server works on regular expressions, not exact matches.
All the regular expressions used for the various fields can be found in autofill_regex_constants.cc.utf8.
From there you can see that the expression for email field is "e.?mail" and for username it is "user.?name|user.?id|nickname|maiden name|title|prefix|suffix"
It appears a similar question has been asked before:
What is the correct way to stop form input boxes auto-completing?
There is an autocomplete attribute you can use in form fields.
<input id="id_login_username" type="text" name="login_username" maxlength="25" autocomplete="off" />

Django formset apparently only printing first form in template (because of invalid markup)

[Edit: See my answer below - the origin of this issue is invalid markup, and browsers working very hard to hide that. ]
I have a formset which definitely should contain two forms, but for whatever reason, I am only getting one form printed in the template.
This is the template line:
<tr id="existing_docs_row"><td colspan="2">{{ existing_articles.management_form }}{% for f in existing_articles %}<div>{{ f }}</div>{% endfor %}</td></tr>
I get the exact same behaviour (less div tags) with:
<tr id="existing_docs_row"><td colspan="2">{{ existing_articles }}}</td></tr>
The management form and first form are created, but not the second. This is what I get in my browser:
<input type="hidden" id="id_form-TOTAL_FORMS" value="2" name="form-TOTAL_FORMS"><input type="hidden" id="id_form-INITIAL_FORMS" value="2" name="form-INITIAL_FORMS"><input type="hidden" id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS"><div><div class="selected_row " id="selected_row"><span class="formlabel"></span><ul>
<li><label for="id_form-0-selected_0"><input type="radio" name="form-0-selected" value="True" id="id_form-0-selected_0"> </label></li>
</ul></div>
<div class="original_filename_row " id="original_filename_row"><span class="formlabel"><span id="for-id_form-0-original_filename-">Original filename:</span></span><div id="id_form-0-original_filename" name="form-0-original_filename">FakeExampleCompanyName.docx</div></div>
<div class="tags_row " id="tags_row"><span class="formlabel"><span id="for-id_form-0-tags-">Tags:</span></span><div id="id_form-0-tags" name="form-0-tags" class="tagarea"><span class="tagitem">England and Wales</span> <span class="tagitem">Private company limited by shares</span> <span class="tagitem">Model articles with amendments</span></div></div>
Breaking in the view, and printing the formset shows that it contains two forms (existing_template_formset is the name of the formset inside the view):
>>> print existing_template_formset <input type="hidden" name="form-TOTAL_FORMS" value="2" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
<div id="selected_row" class="selected_row "> <span class="formlabel"></span><ul> <li><label for="id_form-0-selected_0"><input type="radio" id="id_form-0-selected_0" value="True" name="form-0-selected" /> </label></li> </ul></div> <div id="original_filename_row" class="original_filename_row "><span class="formlabel"><span id="for-id_form-0-original_filename-">Original filename:</span></span><div name="form-0-original_filename" id="id_form-0-original_filename">FakeExampleCompanyName.docx</div></div> <div id="tags_row" class="tags_row "><span class="formlabel"><span id="for-id_form-0-tags-">Tags:</span></span><div class="tagarea" name="form-0-tags" id="id_form-0-tags" ><span class="tagitem" >England and Wales</span> <span class="tagitem" >Private company limited by shares</span> <span class="tagitem" >Model articles with amendments</span></div></div> <tr><th></th><td><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>
<div id="selected_row" class="selected_row "><span class="formlabel"></span><ul> <li><label for="id_form-1-selected_0"><input type="radio" id="id_form-1-selected_0" value="True" name="form-1-selected" /> </label></li> </ul></div> <div id="original_filename_row" class="original_filename_row "><span class="formlabel"><span id="for-id_form-1-original_filename-">Original filename:</span></span><div name="form-1-original_filename" id="id_form-1-original_filename" >FakeExampleCompanyName.docx</div></div> <div id="tags_row" class="tags_row "><span class="formlabel"><span id="for-id_form-1-tags-">Tags:</span></span><div class="tagarea" name="form-1-tags" id="id_form-1-tags" ></div></div> <tr><th></th><td><input type="hidden" name="form-1-id" id="id_form-1-id" /></td></tr>
>>> len(existing_template_formset) 2
As you can see, in both cases, the total number of forms in the formset is 2 (as evidenced in the management form), but the second one is simply not generated.
Has anyone come across this before? How do I fix this?
I'm using django 1.3.1 on python 2.7.2 on windows.
For completeness, here is the code which creates the formset:
class ExistingTemplateFormset(modelformset_factory(ArticlesTemplate, extra = 0, form=ExistingTemplateForm)):
def __init__(self, *args, **kwargs):
super(ExistingTemplateFormset, self).__init__(*args, **kwargs)
for x in self:
x.fields['id'].widget = forms.HiddenInput()
x.fields['original_filename'].editable = False
x.fields['original_filename'].widget = SpanWidget(tag = u'div')
x.fields['tags'].widget= TagArea()
x.fields['tags'].help_text = u''
(TagArea and SpanWidget exist)
In the view:
existing_template_formset = ExistingTemplateFormset(queryset = the_organisation.get_template_articles())
Sharp-eyed readers (which, it turns out, does not include me, hence this problem) will note that my output includes at the end of each form:
`<tr><th></th><td><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>`
Now, when that is substituted into <tr id="existing_docs_row"><td colspan="2">{{ existing_articles.management_form }}{% for f in existing_articles %}<div>{{ f }}</div>{% endfor %}</td></tr> that leads to invalid markup (a tr inside a tr!).
So, it turns out that the template was generating the second form, but the browser's error recovery methods (in chrome, disregarding a lot of the invalid markup; in firefox, floating the second form to elsewhere in the DOM) created the appearance that the second form wasn't being generated.
To summarise: just examining the DOM mislead me. Try to force your browser to choke on errors, and look at the raw markup.