Search
Security

Web Security : Automating with LibWWWPerl - Editing a Page Programmatically

Published 3 min readBy Programming4us Editorial Team
1. Problem

You want to fetch a page from your application, read it, and then modify part of it to send back in your response. For our example, we will modify a page on Wikipedia.

2. Solution

See Example 1.

Example 1. Editing a Wikipedia page with Perl

3. Discussion

This kind of test is most applicable in web applications that change a lot between requests. Perhaps it is a blog, forum, or document management system where multiple users may be simultaneously be introducing changes to the application’s state. If you have to find parameters before you can modify them and send them back, this is the recipe for you.

The script in Example 1 is pretty complex. The main reason for that complexity is the way <textarea> elements are handled in HTML::Parser. Many form elements are self-contained (i.e., the value is inside the element itself) like <input type="hidden" name="date" value="20080101">. In an element like that, you just find the one named “date” and look at its value. In a text area, we have a start tag, an end tag, and the text we care about in between. Our parser, therefore, has a “start” handler and an “end” handler. If the start handler sees the start of the textarea, we check to see if it’s the one we want (the one named wpTextbox1). If we found the textarea<) encoded (like &lt;). We have to decode those because Wikipedia expects raw input (i.e., it wants the real, raw < we want, it sets a signal variable to tell the end handler that we just passed the text we want. The text handler scoops up the “skipped” text from the parser and we’re done. The skipped text has HTML entities (like character). Once we know what we originally received, we will simply append our demonstration text to it.

There’s another bit of special handling we’re doing that relates to the URLs we are GETting and POSTing. We append the action to the URL using concatenation instead of just embedding it in the EDITPAGE constant. That is, we set the URL using $req->uri(EDITPAGE . '&action=edit'). If the ampersand is in the original URL that is passed to HTTP::Request::Common::POST, then the ampersand will be encoded as %26, which won’t be parsed by Wikipedia correctly.