Saturday, May 23, 2015

Unwritten: Tides of Change

It seems painfully obvious now that the only way out was through. 

If I had known then what I know now, I would not have wasted so much time searching for source of my profound sadness. I have realized that the answer to that question must no longer guide me if I am to escape the memories of my past. 

Now, I must ask a different question...

Rather than asking myself, "how did I get here?" I am asking a new one, "how the fuck do I get out?" 

Elyssa D. Durant, Ed.M. © 2006-2015

Saturday, May 9, 2015

Website Hacking 101

Website Hacking 101 : Part II : InfoSec Institute
by Ivan Dimov, resources.infosecinstitute.com
August 28
To view Part I of this article, please visit http://resources.infosecinstitute.com/website-hacking-101/.

In this Part, we are going to briefly introduce Path Traversal, usage of Delimiters, and Information Disclosure attack.

Wee are going to present simple solutions to simplified problems involving the attacks.

Content

Exercise 8: Path Traversal

Figure : A simple webpage in which you choose an article and view it

The website (index.php) in the PathTraversal folder contains a simple form which submits to the same page through the GET request method. Once a choice of article has been made and “View article” has been clicked, the following PHP code executes:

<?php
//If the article GET parameter is set
if (isset($_GET["article"])) {
// Create a div block and fill it with the contents from the file in the GET value.
        echo "<div id='article'>" . file_get_contents($_GET["article"]) . "</div>";
}
?>
The result is the following URL: http://localhost/2/PathTraversal/?article=1.htm

It loads the relevant article file placed in the GET method. The parameter article is formed via:

<select name="article" required=""></select>
And the values are also directly given through the HTML code (the value attribute):

Domain Slamming

Now, legitimate users will use the interface provided in the website to browse it, but with the code as it is we can easily open myriad files they do not want you to open by directly tampering with the URL parameters. Many websites have config directories where they store important data – let’s see if you can do it.

Tasks
Go back one directory and open openme.txt by changing the URL parameters.
We assume that we cannot open the folder config from our computer but only from the local server. Assume you do not know what files there are in the directory. First, you should check whether the directory exists.
The directory exists and now we know that there is HTTPAuth in place. Your task is to somehow find out the username and the hashed password for the folder without using any brute-force or dictionary attacks on the username and password.

Spoiler (Task 2)
If we know that there is a HTTPAuth security mechanism in place, then we can automatically deduce there is an .htaccess file. Therefore, we can open the .htaccess file that we would not be able to open normally via the path traversal vulnerability of the article viewer page.

Figure: Viewing the .htaccess file from the article viewer page

We type http://localhost/2/PathTraversal/?article=config/.htaccess and now we know the path and the file in which accounts and passwords are stored as well as the user that is required to view the folder.

We type the path to the userlist.htpasswd file and get all usernames and passwords:

tomburrows:$apr1$ZF.78h2N$zhAaP2AY6VwxuELizJAwg.

Now, the username is known and we have incredibly reduced our cracking time. HTTPAuth is using UNIX’s “CRYPT” function to encrypt the passwords which is a “one way” encryption method.

Using path traversal, we can also go back several directories and browse to the php.ini and other important configuration files as well.

A sample solution to our path traversal vulnerability
<?php
//If the article GET parameter is set

if (isset($_GET["article"])) {
//Remove any “/” and “.” characters from the GET parameter’s value as this can be used for path traversal 
        $article = str_replace(array("/", "."), "", $_GET["article"]);
// If the file does not exist, print a custom error.
        if (!file_exists($article . ".htm")) {
        echo "<h1>The article does not exist!</h1>";
        }
        else {
//If and only if the file exists – echo out its contents

// Create a div block and fill it with the contents from the file in the GET value.
//Add a mandatory file extension of .htm to the file
        echo "<div id='article'>" . file_get_contents($article . ".htm") . "</div>";
        }
}
The change in the HTML code is that we no longer use the full file name value in the options tags, we just use the name of the file (without its extension so only .htm files would be allowed)

Want to learn more?? The InfoSec Institute Ethical Hacking course goes in-depth into the techniques used by malicious, black hat hackers with attention getting lectures and hands-on lab exercises. While these hacking skills can be used for malicious purposes, this class teaches you how to use the same hacking techniques to perform a white-hat, ethical hack, on your organization. You leave with the ability to quantitatively assess and measure threats to information assets; and discover where your organization is most vulnerable to black hat hackers. Some features of this course include:
Dual Certification - CEH and CPT
5 days of Intensive Hands-On Labs
Expert Instruction
CTF exercises in the evening
Most up-to-date proprietary courseware available
VIEW ETHICAL HACKING

 Keyloggers: How They Work and More
Firstly, checking if the file exists and echoing it out only if it exists prevents another attack – that of information disclosure.

There is a PHP warning thrown out if we type a non-existent file deliberately. Of course, another way to resolve such information disclosure issues is by turning off the display_errors In the php.ini file (this is most desirable if the site is live anyway).

With the above mentioned code we get a clean and neat error that the article does not exist, along with prevention of any path traversal attempts.

Figure: We now receive an error when we try to go back one directory and open the openme.txt file

Note: in old editions of PHP (older than 5.5.3) you could use the %00 marker to end the string abruptly and pass your own file extension in place of the “.htm” one in our solution code.

if (!file_exists($article . “.htm”)) could be exploited in older versions of PHP by typing:

http://localhost/2/PathTraversal/?article=accounts.txt %00

Which is equivalent to:

“accounts.txt.htm” forcing the server to ignore the .htm part of the string.

Exercise 9: Information disclosure

Figure: Comment page

For this exercise, I have created a working but problematic comments page which looks similar to a chat. You have to write a comment, and then you view all the comments up to now. The comments are stored in a .txt file rather than in a database and there is one PHP file that creates new comments and one that displays them on the screen.

//Index.php server-side code

        <?php
                $path = "comments/";
                ?>

                <?php 
                        if ($_SERVER["REQUEST_METHOD"] === "POST") {
                                include("add_comment.php");                   

                        }

//Add_comment.php
<?php 
                        //Open file and create an array with all comment information as indices
                        $comments = file_get_contents($path . "comments.txt");
                        $newcomment = [];
                        $newcomment[] = $_POST["name"];
                        $newcomment[] = $_POST["topic"];
                        $newcomment[] = $_POST["message"];
                        // Convert to string and add a delimiter to store in file
                        $newcomment = implode(":", $newcomment);
                        // Write the string to the file
                        $comments_w = fopen($path . "comments.txt", 'w');

                        fwrite($comments_w, $comments . "n" . $newcomment . ":" ); 
                        // Show all comments
                        include($path . "view_comments.php");

                        ?>
Figure: How the comments file looks

// View_comments.php

        <?php
//Convert to array and echo all out in a certain format within the comments div
$comments = explode(":", file_get_contents($path . "comments.txt"));
echo "<div id='comments'>";
for ($i = 0; $i < count($comments) - 1; $i += 3) {
        echo "<p>User: " . $comments[$i] . "<br> posted about: ".
        $comments[$i + 1] . "<br> and he wrote: " . $comments[$i + 2];
        echo " </p>"; 


}
echo "</div>";

?>
This application works just fine when viewed as is, but imagine if a user enters add_comment.php separately, without the file being included from the index.php. This can easily happen as the name of the service implies the file name, and this particular file name is frequently used, and the fact that add_comment.php is in the same directory facilitates the process.

Figure: Viewing add_comment.php on its own

Now, the attacker would know that we have a variable called $path and he can probably guess that we are setting the path to the comments file as there is a warning that file_get_contents(comments.txt) cannot be opened. Thus, he knows the name of the file that contains all our comments as well. Because the include is failing, he also knows the whole include_path which can also be dangerous. Also, the attacker knows another file in our directory tree (view_comments.php) so he can access it and look for some more errors. He also knows that in this file we are working with the POST values from the form, as he can view the HTML and see they are the same.

This comments form is also vulnerable to diferent code injection attacks. You can easily insert in one of the comment fields to test it out. In that way, the browsers of the users’ will execute any code that you like each time they visit the page.

A probable solution is easy: wrapping the post values in htmlspecialchars() function which converts < and > amongst others as special characters (<, >, etc.) preventing them from being interpreted as code.

$newcomment[] = htmlspecialchars($_POST["name"]);

$newcomment[] = htmlspecialchars($_POST["topic"]);

$newcomment[] = htmlspecialchars($_POST["message"]);

Solution

A simple solution to get rid of all those errors in this example is to wrap the code in add_comment.php and view_comments.php inside the following if statement:

        if (isset($path)) {     
//code here

}
In that way, the code will only execute if the files are included from index.php, presumably.

Of course, that does not handle the issue that users can post the form empty and still view the content and make the application think there is an actual comment, but that can easily be fixed and is not the issue of discussion here.

Displaying errors is good for development purposes but when the application is live and in production – always turn off display_errors from the php.ini

Exercise 10: Delimiters

We will be looking at a vulnerability similar to the one that existed in the old Poster website.

Sometimes, parameters used In the code can be abused by users even when interacting with the interface provided to them.

Open Delimiters folder from your localhost in a browser. There is a users.txt file which contains all the user data. However, access to it is forbidden from the .htaccess file:

<Files "users.txt">
Deny from all
</Files>
Try to open it using the path traversal method of the article viewer, just for practice.

Look at the different data stored there and think about what everything represents.

Try to login with one of the accounts and escalate your privileges to “admin” just by communicating with the website as normal.
Spoiler
http://localhost/2/PathTraversal/?article=../Delimiters/users.txt

//The path in the GET should be valid, but you should fill the path to the index.php.

It should be clear that the “:” character is the delimiter between the different values.

You can test on the login form, but it should be clear that the first word before the first delimiter is the username, the second is the password and the third is the user’s privileges.

The code that extracts the user data one line at a time is the following:

$userlist = fopen('users.txt', 'r');
while (!feof($userlist)) {
        $line = fgets($userlist);
        $acc_details = explode(":", $line);
        $username = $acc_details[0];
        $password = $acc_details[1];
        $access = $acc_details[2];
Then, each line is checked separately with the submitted details to check whether It matches with them:

if ($username === $_POST["name"] && $password === $_POST["pass"]) {
When it find a match, the user can be logged in.

Note that there are many better alternatives than this nowadays, such as using a database and cookies.

When logged in, you have the option to change your username or/and password.

if (isset($_POST["pass"]) && trim($_POST['pass']) !== "") {
                        $userlist = str_replace /* old pass */ ($_POST["userdata-pass"],  */ new pass */$_POST['pass'], $userlist);
                        echo "<em>Password changed to: " . $_POST['pass'] . "</em>
";
And to check the privileges, the script merely checks if there is a substring “admin” in the $access variable.

if (stripos($access, "admin") !== false) {
        echo "<img src="administrator.png" alt="admin" width="480" height="480" /></pre>
<h1>Howdy, admin!</h1>
<pre>
";
}
Thus, it should be clear that you can abuse this mechanism by adding the : delimiter after your password and typing admin after it when you change your password.

Solution to this vulnerability
The solution is easy and is the same as the previous exercise.

We change the code slightly:

                if (isset($_POST["usrname"]) && trim($_POST['usrname']) !== "") {
                        //We remove any delimiters in the new account details an add it to a var
                        $newacc = trim(str_replace(":", "", $_POST["usrname"]));
                        //Then, we replace the old password with the $newacc variable
                        $userlist = str_replace($_POST["userdata-acc"], $newacc, $userlist);
                                echo "<em>Username changed to: " . $_POST['usrname'] . "</em>
";
                }
Besides sniffing and other problems, this website is again vulnerable to probability of information disclosure, as the last iteration of the while loop spills out an empty line and a PHP error would occur each time a wrong password is submitted unless display_errors is set to off.

You can do the following to avoid this as well:

if (trim($line) === "")
                break;
Conclusion

Sometimes the solutions to vulnerabilities are really simple and do not take too much time, you just have to split the application into pieces and test them all apart from the single whole that is the application itself.

Friday, May 8, 2015

Is Social Rejection the Key to Creativity?

Is Social Rejection the Key to Creativity?


On the psychology of why rejection and loneliness may be necessary evils for the creative genius

"In the deepest and most important things, we are unutterably alone, and for one person to be able to advise or even help another, a lot must happen, a lot must go well, a whole constellation of things must come right in order once to succeed." — Rainer Maria Rilke


Vincent Willem van Gogh was born on March 30, 1853, in a small town in the southern Netherlands. At age 13 he attended Willem II College, a nearby middle school. An artist from Paris by the name of Constantijn C. Husymans taught at the school, and it was he who first exposed the young van Gogh to drawing. Two years later, however, van Gogh grew frustrated with his schooling and returned home. "My youth was gloomy and cold and sterile," he would later write to his brother Theo in a series of letters now collected as The Letters of Vincent Van Gogh.

He subsequently moved to Paris and famously made a name for himself as a painter. Still, he suffered often with bouts of depression and gloom. At age 36, he decided to move to Auvers-sur-Oise, a sleepy town in northwestern France, where he could be nearer to Theo and to a psychiatrist named Dr. Paul Gachet, who was recommended to van Gogh by friend and fellow painter Camille Pissaro. Jan Hulsker, a Dutch art historian, notes that upon moving to Auvers-sur-Oise, van Gogh suffered a new crisis, "the starting point for one of the saddest episodes in a life already rife with sad events." For a year van Gogh "had fits of despair and hallucination during which he could not work, and in between them, long clear months in which he could and did, punctuated by extreme visionary ecstasy," writes art critic Robert Hughes.

Around this time, van Gogh wrote another letter to his brother, this time about his loneliness. Even if he were to have a friend for whom he cared, van Gogh felt that it would only serve to lead him away from his art.

"We feel lonely now and then and long for friends and think we should be quite different and happier if we found a friend of whom we might say: 'He is the one,'" van Gogh wrote. "But you, too, will begin to learn that there is much self-deception behind this longing; if we yielded too much to it, it would lead us from the road."

The next year, on July 27, 1890, a 37-year-old van Gogh is alleged to have shot himself in the chest with a revolver. "Some think Van Gogh shot himself in the wheat field that had engaged his attention as an artist of late; others think he did it at a barn near the inn," writes biographer Ingo Walther. Van Gogh walked to the Auberge Ravoux, a lodge where he had recently been staying. Two doctors attended to him but without a trained surgeon present the bullet could not be removed. Theo was notified and rushed to be with his brother. The next evening, however, an infection caused by the bullet killed van Gogh. He spent his final evening smoking a pipe and chatting with Theo. His final words were, "The sadness will last forever."

Van Gogh likely had a cadre of mental issues, none of which were suitably diagnosed while he was alive. Yet what seemed to weigh heaviest on him was the inevitability of his loneliness. According to his letters to Theo, he felt he had one of two options: content himself with loneliness or try to countenance his loneliness with friendships thereby derailing his creativity ("lead us from the road," as he wrote).

Aldous Huxley wrote, "If one's different, one's bound to be lonely," and upon thinking about it even a little, it quickly becomes apparent that many of history's creative geniuses have been deeply lonely people. There is the obvious reason for this: dedicating oneself to an artistic pursuit means one has little time for social endeavors. This is what has frustrated flamboyant, gregarious writers like F. Scott Fitzgerald and Henry James, both of whom wrote about the dreadful isolation necessary to turn out great fiction. But whether it's the mysteriously secretive writing careers of J.D. Salinger or Donna Tartt, the well-known loneliness of Joseph Conrad ("we live as we dream — alone") or the friendship-loneliness conundrum of van Gogh, it becomes apparent that something else is at play. Loneliness is not just sufficient for creativity; it is necessary. It is almost as if one can only be truly creative when one detaches from society.


"Starry Night Over the Rhone," 1888, Van Gogh, Musée d'Orsay, Paris 


Sharon H. Kim is an assistant professor at Johns Hopkins University who focuses on individual and group creativity. She did her undergraduate work at the Ohio State University and completed her doctorate at Cornell. She has jet-black hair and chunky black spectacles to match. In her most recent study, she found evidence that people tend to be more creative if they have been socially rejected.

What is perhaps most interesting about her findings is that no actual social rejection has to have taken place, the creative must only feel rejected in some way and must establish a feeling of independence, of being "different" than his or her peers.

In the 1956 book The Outsider, Colin Wilson claimed that creative geniuses tend to live on the margins of society, rejected and non-conformist. Yet, a neurological nuance must be added to Wilson's well-known theory. When creativity becomes all that matters — when dreams of fitting in with society and having a white picket fence fall by the wayside — then one's cognitive focus can move from socio-cultural ones (fitting in) to creative pursuits(standing out).

"Given that creative solutions are by definition unusual, infrequent, and potentially controversial, they are stimulated by the desire to stand out and to assert one's uniqueness," writes Kim. "The experience of rejection may trigger a psychological process that stimulates, rather than stifles, performance on creative tasks."

Scholars didn't always think like this. In fact, Kim quotes a series of studies, principally Roy Baumesiter's 2005 study, which claimed that social exclusion hinders cognitive performance and therefore decreases one's ability to be creative. But Kim flatly rejects this claim, asserting that loneliness and the feelings of rejection instead allow one to better focus cognitive performance on a single, creative task.

Think of it like this: You go to see a play with a friend. During the play you'll likely be wondering what your friend is thinking of the show, what quarrels he or she will take with it, what your discussion will be like on your walk home. But if you go to the theatre by yourself, all of your concentration can be directed on what's happening on stage. Your mental energy is focused.

When we let our focus shift away from the people and things around us, we are better able to engage in what's called "meta-cognition," or the process of "thinking critically and reflectively about our own thoughts," as psychology professor Gregory Feist says.

The difficulty lies in striking a balance. There is solitude, which can lead to meta-cognition and creative focus. But there is also, as van Gogh experienced off and on throughout his life, crippling loneliness that sets the artist back. The gap is razor-thin. Loneliness and depression (Hemingway called depression "the artist's reward") are central to why so many great artists from Hemingway to Plath to Hunter S. Thompson have taken their own life. Sartre is alleged to have said, "If you're lonely when you're alone, you're in bad company," but parsing the distinction between solitude — where one is willfully and happily alone — and loneliness — where one is desperate and depressed to be alone — is a task that should not be taken lightly. "Solitude gives birth to the original in us, to beauty unfamiliar and perilous, to poetry," wrote Thomas Mann. "But also, it gives birth to the opposite: to the perverse, the illicit, the absurd." He might have added: to the crippling, the desperate, the depressing.


Vincent Van Gogh (left) and his younger brother, Theo (right), 1887

Modern studies have shown how great a challenge it is to differentiate between loneliness and solitude. One wants to "treat the loneliness while strengthening the solitude," writes psychotherapist Edward Tick. The trouble is that solitude may not be enough for creative genius because it entails no rejection. Loneliness, however, is the product of rejection, either a rejection inflicted by society or inflicted on oneself and therefore lends itself most to creativity.

Yet, one must wonder, is it possible that creating great art is such a momentous act that loneliness and social rejection cease to matter? In a letter to a seventeen-year-old aspiring author called Leonard, the French-born author Anaïs Nin wrote, "Great art was born of great terrors, great loneliness, great inhibitions, instabilities, and it always balances them." The composer Pyotr Ilyich Tchaikovsky also seemed to strike this balance. He was notoriously depressed and, as a gay man in nineteenth-century Russia, surely felt socially rejected. But when he had a creative breakthrough all of that went away. "It would be vain to try to put into words that immeasurable sense of bliss which comes over me directly a new idea awakens in me and begins to assume a different form," he wrote to his financier and friend Nadezhda Filaretovna von Meck in 1878. "I forget everything and behave like a madman. Everything within me starts pulsing."

But this may be a balance that only a select few can endure. Creativity stems from the ability to make original, unique connections, to bind together disparate information in a way that few are able to accomplish. "Creative people are better at recognizing relationships, making associations and connections, and seeing things in an original way — seeing things that others cannot see," writes neuroscientist Nancy C. Andreasen. Often, the only way to see what others cannot see is to experience what others cannot imagine experiencing: rejection, isolation, loneliness. The trouble is that rejection, isolation, and loneliness are awful emotions to have to endure. Few can withstand them for a few years. Almost no one can withstand them for a lifetime.

Even a genius like van Gogh could not deal with the social detachment that he felt his creativity demanded. Still, he felt it worthwhile. On October 14, 1875, van Gogh wrote another letter to brother, counseling him to reject society. "Seek only for light and freedom and do not immerse yourself too deeply in the worldly mire," he wrote.

Six months after Vincent died of an infection, Theo died as well. Theo's medical report, according to biographer Wouter van der Veen, noted that he died of dementia paralytica brought on by "chronic disease, overwork, [and] sadness." Van der Veen also wrote that Theo's health degenerated in large part due to his brother's death. Without Vincent, Theo, who also struggled with loneliness, felt more alone than ever.

Finally, in 1914, over twenty years after Theo's death, Theo's body was exhumed and moved to Auvers-sur-Oise to be next to Vincent's grave. Now the brothers could rest — together.

^ed 
Sent from my BlackBerry® RIM Job