Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - 2Fac3R

#201
También:

mysql -h <host> -u <user> -p

Zalu2
#202
Talleres Underc0de / Re:Taller PHP #1
Febrero 18, 2013, 06:02:38 PM
Pues acá andamos, cualquier duda es bienvenida!
Zalu2
#203
Off Topic / Re:[Duda] Programación en PHP.
Febrero 15, 2013, 09:35:41 PM
Pasate por la sección que tenemos de PHP y ahí hay mucha información al respecto!
Zalu2
#204
Modifica:

Código: php

$query = mysql_query('SELECT * FROM usuario WHERE USER("'.mysql_escape_string($nick).'")');


Por:

Código: php

$query = mysql_query("SELECT * FROM usuarios WHERE USER = '".mysql_real_escape_string($nick)."';");


Te recomiendo empezar a usar PDO, la API mysql_* será removida en futuras versiones de PHP.

para verificar si hay un usuario con ese nick, puedes usar mysql_num_rows() o en PDO rowCount() ;), curratela un poco y me dices si tienes dudas...
Zalu2
#205
Back-end / [Tool] Is Online v2.0 (By 2Fac3R)
Febrero 07, 2013, 09:13:32 PM
Buenas, acabo de mejorar el código que tenía de este pequeño script en php, sirve para verificar si un servidor está online. Tiene diseño kaker xD

Código: php

<!DOCTYPE html>
<title> Is online? v2.0 By 2Fac3R</title>
<style>
body,html{
background-color:black;
color:green;
}
#ok{
font-weight:bold;
}
#bad{
font-weight:bold;
color:red;
}
</style>
<center>
<pre>
.___         ________         .__  .__            _________
|   | ______ \_____  \   ____ |  | |__| ____   ___\_____   \
|   |/  ___/  /   |   \ /    \|  | |  |/    \_/ __ \ /   __/
|   |\___ \  /    |    \   |  \  |_|  |   |  \  ___/|   |   
|___/____  > \_______  /___|  /____/__|___|  /\___  >___|   
         \/          \/     \/             \/     \/<___>   
</pre>

<?php
/*
¿Is online? 2.0 By 2Fac3R
Verificar si un servidor esta online
*/
$page = htmlentities($_POST['page'], ENT_QUOTES ,'utf-8');
$send = $_POST['send'];

function verificar($url){
if(filter_var($url,FILTER_VALIDATE_URL) or filter_var($url,FILTER_VALIDATE_IP)){
echo fopen($url,'r') ? "$url <div id='ok'>Online</div>" : "$url <div id='bad'>Offline</div>";
}else{
echo '<script>alert("URL/IP no valida!");window.location=""</script>';
}
}

if(!empty($page)){
verificar($page);
}else{
if(isset($send)){
?>
<script>
alert("Debes ingresar una URL!");
window.location=""</script>
<noscript>
<?die("Debes ingresar una URL! <a href=''><b> Regresar! </b> </a>")?>
</noscript><?
}
?>
<form action="" method="POST">
URL: <input type="text" name="page" value="http://">
<input type="submit" name="send" value="Comprobar!">
</form> <br> <i>By 2Fac3R</i> <br> <br>

<?}?>
<br><b>Gr33tz to:</b> <br> <br>
   
   xt3mp, arcangel_nigth, ANTRAX, 11Sep, Kr34t0r, GAMARRA, SkippyCreammy, v1c0_h4ck <br>
   w4rning, Snifer, arthusu, Kodeinfect, [Q]3rV[0], WilyXem, m3x1c0h4ck, etc, etc, etc ... <br> <br>
   <a href="http://www.underc0de.org"><b>Underc0de.Org</b></a>
   </center>


Espero les sirva de algo :P
Zalu2
#206
Back-end / [ENG] Validation (Hashphp.org)
Febrero 07, 2013, 09:08:36 PM
Validating User Input

As many of you might be aware, one of the staples of any web application security is to make sure that data passed to you from the user won't break your application or otherwise damage your data. Just like you'd check to see who is at the door of your house before you let them in, you'd check user supplied data to see if it is acceptable for whatever you intend to use it for.

Another reason to validate input is simply because you can provide more intuative responses to the user. They may hit a letter by accident while typing in a number. It is far more clear to the user if you inform them that they've made a mistake and allow them to correct it, rather than have the application break, or worse, have the application continue with an unexpected result.

In PHP, user input arrives as one of two types: an array, or a string. Since the most common form of validation involves checking to see if the user has provided a valid integer representation inside one of the string values, we will focus on this point.

What Could Possibly Happen If I Don't?

Well, it largely depends on what your application is doing. It could be as simple as throwing a big ugly error, but it could also be a lot worse. Take the following highly insecure code example:

Código: php
<?php

$user_id = 1;
$connection = mysql_connect('myserver.com', 'username', 'password');
mysql_select_db('my_database', $connection);
$query = "SELECT secret_data FROM mytable WHERE string_col = '{$_GET['string_col']}' AND int_col = {$_GET['int_col']} AND user_id={$user_id}";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);

?>


This piece of code seems simple enough. Open a connection to 'myserver.com', and select a row from 'mytable'. What could possibly go wrong? As it turns out, quite a lot. This particular piece of code has two very distinct problems which we'll look at.

First off, we're not validating the user input at all. This is a problem in cases where the program expects a certain kind of input and we don't explicitly check for that input. I've purposefully labeled the columns "int_col" and "string_col" to let you know what types they are in the table. Notice that one is specifically an integer. Now, if the user enters a non-integer value in to that column, the query will error.

What not to do

Many people will be tempted to use one or more of the following when faced with validating integers:

    Cast the input to INT
    Use ctype_digit()
    Use is_numeric()

These are all the wrong ways to approach this problem.

Why casting to INT is bad

Casting to INT is often not a good idea from the standpoint that the behaviour is confusing to the user. For example if they accidentally enter the value "123r5" casting to INT will make this value "123". This could lead to results that simply don't make sense from the user's perspective. It is a much better idea to reject the input and ask them to enter a whole number.

Why ctype_digit() is bad

ctype_digit() has two main flaws when dealing with integer validation:

    It is incapable of dealing with signed numbers, so we can't validate negative values
    If the number is cast to an INT, it will treat the values from 0 - 255 as a character rather than a number

Why is_numeric() is bad

Many people reach for is_numeric() thinking this is a good approach, and it will seem to work just fine. However the problem with is_numeric() isn't that it can't detect an integer, it is that it detects a lot more than just integers. All of the following are valid numbers to is_numeric():

    1
    1.123
    0xFF
    +0123.45e6

See the problem? If we really want just an integer, this function is too broad.

So, how do I fix it?

The best way to fix this sort of validation issue is to use php's filter library. This library is designed to help you check and sanitize user input. For example, we could change our application to use filter_var() and it might look like this:

Código: PHP
<?php

// do some validation first!
if (filter_var($_GET['int_col'], FILTER_VALIDATE_INT) === false) {
  die('You must enter a valid integer!');
}

$user_id = 1;
$connection = mysql_connect('myserver.com', 'username', 'password');
mysql_select_db('my_database', $connection);
$query = "SELECT secret_data FROM mytable WHERE string_col = '{$_GET['string_col']}' AND int_col = {$_GET['int_col']} AND user_id={$user_id}";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);

?>


Now if we try to enter anything but a number for $_GET['int_col'] it won't get to the point where it asks MySQL for data. These kinds of validations are perfect for form data, and can allow you to decide to render the form again with errors to inform the user that they have made a mistake, and to try again. However, we're not quite finished here just yet. There is a remaining problem. The dreaded SQL injection.

What Is an SQL Injection Attack?



An SQL injection attack is when a user injects SQL commands in to an unprotected SQL query. This can lead to a number of issues, including modifying rows you didn't intend for the user to modify, dropped tables, deleted rows, and access to possibly sensitive data. It is critical that you learn and understand how these attacks work. SQL injection attacks are arguably the most common way PHP websites get exploited. The importance can not be overstated.

Initially, in code, the part where we build our query looks like this:

Código: php
<?
$query = "SELECT secret_data FROM mytable WHERE string_col = '{$_GET['string_col']}' AND int_col = {$_GET['int_col']} AND user_id={$user_id}";
?>


If I call: You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login then:

    $_GET['string_col'] has a value of "some_data' OR 1=1 -- "
    $_GET['int_col'] has a value of "1"
    $user_id has a value of "1" (we set this in code, it is not a user supplied value)

When the code gets to the point where it builds the query, it winds up looking something like this:

Código: sql
SELECT secret_data FROM mytable WHERE string_col = 'some_data' OR 1=1 -- ' and int_col = 1 and user_id = 1


Notice the double dash. This is a mysql comment token, and it will cause everything after it to be ignored. To MySQL, the query now looks like this:

Código: sql
SELECT secret_data FROM mytable WHERE string_col = 'some_data' OR 1=1

Which is clearly now ignoring our $user_id variable, and the int_col clause in favour of what the attacker has chosen. You can probably imagine how bad this could get if instead of a SELECT the query happens to be an UPDATE or DELETE. Depending on the database library, it may also allow multiple queries to be specified in the same string, meaning the innocent SELECT could also have an entirely new query piggy-backed on to it.

How to Deal With Injection Attacks

So, we started off protecting our integer value, but what about the string value? Technically, a string could be any sequence of characters. If your program needs to allow them to be anything, we still have to protect our code. So how do we do this?

As with many things, there are several ways to deal with this problem depending on what database library you're using. To start off, we'll look at the standard mysql library used in the previous examples. The best way to avoid injection attacks when dealing with the standard mysql library, is to escape your parameters. We can do this with mysql_real_escape_string().

For example:

Código: php
<?php

// do some validation first!
if (filter_var($_GET['int_col'], FILTER_VALIDATE_INT) === false) {
  die('You must enter a valid integer!');
}

$user_id = 1;
$connection = mysql_connect('myserver.com', 'username', 'password');
mysql_select_db('my_database', $connection);
// escape parameters after the database connection is open because it asks the database how to escape things
$escaped_int_col = mysql_real_escape_string($_GET['int_col']);
$escaped_string_col = mysql_real_escape_string($_GET['string_col']);
$query = "SELECT secret_data FROM mytable WHERE string_col = '{$escaped_string_col}' AND int_col = {$escaped_int_col} AND user_id={$user_id}";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);

?>


So what's happening here? Consider our previous example where the attacker was sending a malicious string.

    some_data' OR 1=1 --

now becomes

    some_data\' OR 1=1 --

See the subtle difference? The "\" character makes it so that the quote in the string is now harmless, and instead of closing the value prematurely it will just be a part of the string. This is just one of the many bad characters mysql_real_escape_string() will fix for you.

Using Prepared Statements to Stop Injection Attacks

We've stopped the injection attack! Hurray! But what if there were an easier, better way to do all this? The good news is, there is! PHP comes with another database library to deal with MySQL. It is called PHP Data Objects or PDO for short. This library can use drivers for many different database types, and supports a very important feature known as prepared statements, sometimes also known as parametrized queries.

So what do these prepared statements do? Well, quite a lot. They allow us to design our query ahead of time and to put placeholders in the areas where our user supplied data will go. Then when we ask the library to inject the values, it automatically escapes them for us. Consider this example:
Código: php

<?php

// do some validation first!
if (filter_var($_GET['int_col'], FILTER_VALIDATE_INT) === false) {
  die('You must enter a valid integer!');
}

$dsn = 'mysql:dbname=my_database;host=myserver.com';
$username = 'username';
$password = 'password';
$user_id = 1;

// Set up PDO
$pdo = new PDO($dsn, $username, $password);
// Our parametrized query using placeholders.  No need for quotes around values, it will do this for us.
$query = "SELECT secret_data FROM mytable WHERE string_col = ? AND int_col = ? AND user_id = ?";
// our input values in order for the place holders.  No need to escape, it will do it for us!
$parameters = array($_GET['string_col'], $_GET['int_col'], $user_id);
// Prepare the query
$statement = $pdo->prepare($query);
// execute the query with our parameters
$statement->execute($parameters);
// Get the first returned row
$row = $statement->fetch(PDO::FETCH_ASSOC);

?>


Not only is this method much cleaner, but we can't forget to escape our parameters because PDO is kind enough to do it for us.

Another advantage of prepared statements is that you can use the prepared statement over and over by simply replacing the parameters and executing it again. Many servers detect that you're doing this, and even make the query faster by performing server-side optimizations.

Fuente/Source: You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
#207
Back-end / Re:Filtro inyeccion XSS y SQL
Febrero 06, 2013, 11:40:55 PM
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
... lo prefiero mas que PDO

¿Alguna razón en especial?
#208
Back-end / Re:Filtro inyeccion XSS y SQL
Febrero 06, 2013, 11:18:58 PM
Buen código man, te dejo unas recomendaciones:

1.- Usa code=php en el BBCode para que haga un higthlight al código y así es más legíble ;)

2.- Tienes un error en la siguiente parte:

Código: php

<?
$val = htmlspecialchars ($val, ENT_QUOTES, 'UTF-8')
?>


Te falta cerrar ";" :P

3.- La API mysql_* va a ser removida en futuras versiones de PHP, tratemos de usar "lo nuevo" y "seguro" que es PDO y MySQLI

4.- Cuando ingreses datos a una db lo remendable es limpiarla de etiquetas HTMl con strip_tags() y insertarla con PDO o MySQLI .

Espero te sirvan de algo ;)
Zalu2
#209
Back-end / Re:Comillas y sus usos.
Febrero 05, 2013, 03:58:52 PM
Muy bueno, sólo comentar que existe un tipo más de "comillas", las backticks.

Ejemplo:
Código: php

<?php
$res = `ls -la`;
echo $res;
?>


Devuelve el resultado de ejecutar el comando "ls -la" en la consola (en windows usen dir :P ).
PD: No confundas con comillas simples ;)

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
Zalu2
#210
Off Topic / Re:Me gusta ser portero
Febrero 05, 2013, 11:58:11 AM
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
A mi me parece muy bien que sean porteros y que os guste el fútbol y tambien me parece muy bien que tengaís la libertad de publicación de esta clase de temas en el off-topic pero desde todo el respeto me parece que aun siendo una zona OFF-TOPIC no merece ser llenada de post como estos.

Me explicaré mejor , me gusta mucho el meme "ola ke ase" y no por eso publico un tema diciendo "ola ke ase" mola!!
Con esto no quiero realizar criticas a nadie solo ofrecer la oportunidad de que reflexionen sobre lo que es el foro , no quieran convertirlo en una zona de terapias.

Una cosa es el deporte y otra cosa son los estúpidos memes :P , no seas amargado  ;D
Zalu2
#211
Off Topic / Re:Me gusta ser portero
Febrero 04, 2013, 02:07:35 PM
Igual soy portero, no es por presumir pero mi equipo fue bi-campeón el año pasado y subcampeón el semestre pasado, aparte ibamos en tercer lugar en un torneo de por acá :P . a ver cómo me va este semestre jejeje.

Me gusta la porteria aunque tenga las "dificultades" que mencionas, también a veces soy medio izquierdo ;)
Zalu2
#212
Actualizado : 01/02/2013

Zalu2
#213
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
muy pero muy interesante... el servicio multiconversor de underc0de no anda muy bien voy a charlar con antrax para cambiarlo por el tuyo.

saludos!

Me parece perfecto, cualquier cosa me avisas ;)
Zalu2
#214
Back-end / Re:[PHP] Who visits my website?
Febrero 02, 2013, 12:53:29 AM
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
esta bien, salvo que hay detalles, por ejemplo que no hallas establecido el ámbito de las funciones.

o esto:
$db = 'test';

en cualquier lenguaje te dirían que esa es la función de una constante, que a lo largo del código no cambia, por lo que no es variable.

saludos!

Es para que el usuario lo cambie por sus datos:

Código: php

# Cambia por tus datos!
$db = 'test';
$table = 'contador';
$user = 'root';
$pwd = 'toor';
#----------------------


Por lo cual lo convierte en variable dependiendo de la base de datos de quien lo uso :P
Zalu2
#215
Versión 2.2 de el conversor de string (convertidor), mejoré el código y agregué nuevos tipos de cifrado!

Tipos de cifrado
- Encode
- Decode
- gzinflate
- Encode UTF-7
- ASCII
- MD5
- SHA1
- Base64 encode
- Base64 decode
- Binario To Decimal   
- mcrypt


Código: PHP

<title> Conversor de string By 2Fac3R v2.2 </title>
<?php
/*
Conversor de string By 2Fac3R v2.2

  */
$string = $_POST['str'];
$conv = $_POST['convertir'];
$send = $_POST['send'];
function res($func){
global $string;
echo "Resultado: <br> <textarea cols='80' rows='5'>$func</textarea><br>";
echo "Normal: <b>".htmlentities($string,ENT_QUOTES)."</b> <br>";
echo "<a href=''> Regresar! </a>";
}
if(!empty($string)){
switch($conv){
case 'bin2hex':
res(bin2hex($string));
break;
case 'encode':
res(urlencode($string));
break;
case 'gzinflate':
res(gzinflate($string));
case 'decode':
res(htmlentities(urldecode($string)));
break;
case 'utf-7':
res(mb_convert_encoding($string,'UTF-7'));
break;
case 'ASCII':
echo "Resultado: <br><textarea>";
for($i=0;$i<strlen($string);$i++){
$obt=ord($string[$i]);
$ascii=$obt.',';
echo $ascii;
}
echo "</textarea><br> Normal: <b>".htmlentities($string)."</b><br><a href=''> Regresar! </a>";
break;
case 'MD5':
res(md5($string));
break;
case 'SHA1':
res(sha1($string));
break;
case 'Base64_encode':
res(base64_encode($string));
break;
case 'Base64_decode':
res(base64_decode($string));
break;
case 'bindec':
res(bindec($string));
break;
case 'mcrypt':
res(crypt($string));
break;
default:
die("Ha habido un error <a href=''> Regresar! </a>");
break;
}
}else{
if(isset($send)){?>
<script>alert("Campo de texto vacio");</script>
<noscript>Campo de texto vacio <br> <font color="RED"> Active el javascript para una mejor visualizaci&oacute;n </font></noscript>
<?}?>
<!-- Conversor de string By 2Fac3R v2.2 -->
<form action="" method="POST">
<select name="convertir">
<option value="bin2hex"> BinToHex </option>
<option value="encode"> Encode </option>
<option value="decode"> Decode </option>
<option value="gzinflate"> gzinflate </option>
<option value="utf-7"> Encode UTF-7</option>
<option value="ASCII"> ASCII </option>
<option value="MD5"> MD5 </option>
<option value="SHA1"> SHA1 </option>
<option value="Base64_encode"> Base64 encode</option>
<option value="Base64_decode"> Base64 decode</option>
<option value="bindec"> Binario To Decimal</option>
<option value="mcrypt">mcrypt</option>
</select>
<input type="text" name="str">
<input type="submit" name="send" value="Convertir!">
</form>
<?}
/*
* .- Underc0de.org -.
*    v2.0 2013
*
* Gr33tz to:
*
* xt3mp, arcangel_nigth, EddyW, ANTRAX, 11Sep, Kr34t0r, GAMARRA, SkippyCreammy, v1c0_h4ck, w4rning, Snifer,
* arthusu, Kodeinfect, [Q]3rV[0], WilyXem, m3x1c0h4ck, etc, etc...
*
* */
?>


Espero les sirva como a mi ;)
Zalu2
#216
Presentaciones y cumpleaños / Re:Hola a todos!!
Enero 31, 2013, 02:50:08 PM
Bienvenido!

Pasate por las reglas y por los talleres, hay uno de python ;)
Zalu2
#217
Back-end / [PHP] Who visits my website?
Enero 31, 2013, 02:39:58 PM
Les dejo un pequeño script que acabo de terminar, es un simple contador de visitas (la versión anterior ya la había posteado), está en su versión 2.0.

Agregué PDO y mejoré un poco el código.

contador.php

Código: php

<title> Who visits my website By 2Fac3R v2.0 </title>
<?php
/*
   Who visits my website By 2Fac3R v2.0
  Con PDO
*/

class contar{


function datos($dbname,$user,$pwd){

$dsn = "mysql:host=localhost;dbname=$dbname";
$this -> con = new PDO($dsn,$user,$pwd);

}

function agregar($table){

$ip = $_SERVER['REMOTE_ADDR'];
$pag = __FILE__;
$ins = $this -> con -> prepare("INSERT INTO $table(ip,page) VALUES(:ip,:pag)");
$ins -> bindParam(":ip",$ip,PDO::PARAM_STR);
$ins -> bindParam(":pag",$pag,PDO::PARAM_STR);
$ins -> execute();

}

function view($table){
$mos = $this -> con -> query("SELECT * FROM $table");
echo $mos -> rowCount();
}

}

# Cambia por tus datos!
$db = 'test';
$table = 'contador';
$user = 'root';
$pwd = 'toor';
#----------------------

$contar = new contar;
$contar -> datos($db,$user,$pwd);
$contar -> agregar($table);
$contar -> view($table);


/*
* .- Underc0de.org -.
*    v2.0 2013
*
* Gr33tz to:
*
* xt3mp, arcangel_nigth, EddyW, ANTRAX, 11Sep, Kr34t0r, GAMARRA, SkippyCreammy, v1c0_h4ck, w4rning, Snifer,
* arthusu, Kodeinfect, [Q]3rV[0], WilyXem, m3x1c0h4ck, etc, etc...
*
* */
?>


Guarda el archivo que se visitó y la IP que la visitó.

contador.sql

Código: text

CREATE TABLE contador( -- Cambiar por nombre de tabla
ip varchar(12),
page text
);


Lo hize más que nada para desoxidarme de la POO en PHP, aunque no apliqué mucho pero sirve de algo xD
Zalu2
#218
Python / Re:[Scr] Ofuscando vectores XSS.
Enero 31, 2013, 12:59:52 PM
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
Gracias por las 2 observaciones, pero queria hacerlo con el for para practicar  ;D
Respecto al "clear", si es bajo windows cambienlo a "cls".

-Saludos-

Puedes hacer esto:

Código: python

if os.name == "posix":
    c = 'clear'
else:
    c = 'cls'
   
os.system(c)


Así es compatible tanto en windows y en linux sin que el usuario tenga que cambiar a mano el código ;)
Zalu2
#219
Back-end / Re:¿Que es un framework?
Enero 31, 2013, 12:22:39 AM
Vale, creo que me toca probar, igual por el momento no me llama mucho la atención el uso de frameworks.
Zalu2
#220
Back-end / Re:¿Que es un framework?
Enero 30, 2013, 10:15:51 PM
Sólo he usado el JQuery como framework de javascript pero en php no jeje, me recomiendas alguno que hayas usado?

PD: Te faltó el famoso pasado de moda You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login ;)

Zalu2