Recursividad - Fibonacci

June 28, 2008

Los programas y codigos expuestos fueron probados antes de ser publicados.

/*
Nombre: Codigo Fibonacci
Autor: Julian Rodriguez
Tema: Recursividad
Fecha: 27/Junio/2008
*/
#include <iostream>
using namespace std;

int fibonacci(int n); // Funcion Recursiva
int main()
{
int n, resultado; // Variables

cout << "Escribe el numero de posicion: ";
cin >> n;

resultado = fibonacci(n);
cout << endl << "[+]Posicion: " << n << " Valor: " << resultado << endl;;

return EXIT_SUCCESS;
}

int fibonacci(int n)
{
cout << "[-]Procesando: Fib(" << n << ")" << endl;
if( n < 3 )
{
return (1);
}
else
{
cout << "Fib(" << n-2 << ") - " << "Fib(" << n-1 << ")" << endl;
return ( fibonacci(n-2) + fibonacci(n-1) );
}
}

Recursividad - Potencias

June 28, 2008

Los programas y codigos expuestos fueron probados antes de ser publicados.

/*
Nombre: Codigo Fibonacci
Autor: Julian Rodriguez
Tema: Recursividad
Fecha: 27/Junio/2008
*/
#include <iostream>
using namespace std;

int funcion(int n, int p);
int main()
{
int resultado, n, p;

cout << "Escribe un numero: ";
cin >> n;
cout << "Escribe la potencia: ";
cin >> p;

resultado = funcion(n, p);
cout << "Numero " << n << " elevado a la " << p << "; Resultado = " << resultado;
cout << endl;
getchar();

return EXIT_SUCCESS;
}

int funcion(int n, int p)
{
if(p == 1)
{
return n;
}
else
{
return ( n * funcion(n, p-1) );
}
}

Overloading Functions - Sobrecargar Funciones

June 28, 2008

Overloading Functions - Sobrecargar Funciones

Autor: Julián Rodríguez

// Los programas y codigos expuestos fueron probados antes de ser publicados //

Bueno pues este sera el tema que veremos el overloading de funciones como se le conoce
en ingles, el nombre en español podria traducirse literalmente como la sobrecarga de
funciones. Vamos a ver un ejemplo de esto :

Sobrecargar Funciones : Crear mas de una funcion con el mismo nombre.

int funcion(int, int)

int funcion(long, long)

int funcion(long)

Para que dos funciones puedan tener el mismo nombre deben de tener diferente tipo de
parametros como se puede apreciar en los ejemplos citados; a esto tambien se le llama
polimorfismo funcional.

  • Esto de que nos puede servir ?

Citare un ejemplo de leve codigo para que vean que en vez de estar creando diferentes
funciones podemos hacer las mismas funciones pero con el mismo nombre, la funcion correcta
se utilizara cuando los parametros concuerden en el tipo.

int funcionint (int);
long funcionlong (long);
float funcionfloat (float);


Polimorfismo Funcional

int funcion (int);
long funcion (long);
float funcion (float);
  • Ejemplo

Para dejar a un lado el aspecto teorico dejare un codigo para que se comprenda mas
practicamente que es lo que significa Sobrecargar Funciones, Overloading Functions o
conocido tambien como Polimorfismo Funcional.

#include <iostream>
#include <cstdlib>
using namespace std;

int Doble(int);
long Doble(long);

int main()
{
int myint = 100;
long mylong = 650000;

cout << "Mi Integer: " << myint << endl;
cout << "Mi Long:    " << mylong << endl;
getchar();

int Doblemyint;
long Doblemylong;

Doblemyint = Doble(myint);
Doblemylong = Doble(mylong);

cout << "Doble Integer: " << Doblemyint << endl;
cout << "Doble Long:    " << Doblemylong << endl;
getchar();

return EXIT_SUCCESS;
}

int Doble(int valor)
{
return (2*valor);
}

long Doble(long valor)
{
return (2*valor);
}

Cross Site Request Forgery - CSRF

June 27, 2008

-[ INFOS ]——————————————————————–
Title: “Cross Site Request Forgery: the Sea Surf”
Author: Nexus
Website: http://nexus.playhack.net
Date: 2007-04-29, Updated in 2007-05-20 (ISO 8601)
———————————————————————————

-[ SUMMARY]—————————————————————
0×01: Hello World
0×02: Introduction
0×03: About Authentications
0×04: Difference between XSS and CSRF
0×05: Get deep in CSRF
0×06: Attack Points
0×07: Prevention
0×08: Conclusions
———————————————————————————

—[ 0x01: Hello World ]
Yo!
Classical title for the first paragraph indeed :) Don’t think there’s a better name out there! Ok, i know it’s clueless, but let me do the ritual thanks and shoutouts and then i’ll move on serious business!

Intake: Actually some coke only, it’s too hot for eating anything :Q
Music: Rage Against The Machine - Know your Enemy

Shoutouts: as it comes all my playhack.net bros (Omni, GOD, Null and all the users), str0ke (the c00lest guy out there :P) and my girlfriend, who’s having a bath right now and giving me the time to write this stuff (don’t tell her, she still think i’m working :o) and obviously everyone reading this paper. Thanks!
—————————————————————————–[/]

—[ 0x02: Introduction ]
Today we talk about Cross Site Request Forgery (also known as XSRF) abbreviated in CSRF, from which pronounce has come the friendly name “Sea Surf” ;)
Following the previous papers on Cross Site Scripting written by me, i thought it was an obvious step to deal with this theme: here i am then!

This kind of vulnerability, which is very common and understimated, permits to make a victim user to send any kind of HTTP request to a website in which he is logged in and trusted in some way.

In this way the attacker, forging some malicious HTML or JavaScript code, uses an opened session of the victim to make HIM doing actions, which really  complicates the identification of a CSRF attack.

This Session Riding could easily be taken in action with markup languages (such as Blog’s and Wiki’s syntax) and BBcode too.
—————————————————————————–[/]

—[ 0x03: About Authentications ]
Commonly when a user logs into a trusted website, the authentication system will flag this person with a “token” that tells to the website that the current user is authed and authorized to visit some reserved pages and services.

These “tokens” are realized with the creations of Cookies and Sessions, commonly generated with some hashed or encoded number , which strictly identify a single user.

Anytime this user logs into the website with his own credentials he will be flagged and a new session will be generated, and meanwhile an attacker could easily makes some unauthorized actions in the “ward” of that website ;)

It could looks like something quite un-dangerous, because only an idiot user will accept any kind of request that will disfrut his own authentication: great mistake! Don’t ever understimate the power of a sweet Cookie! :P

Cookies are the aim of the most XSS attacks because permits an instant access to any kind of confidential and private service an user has privileges on: the CSRF is even more powerful, because disfruts the current session and cannot be avoided easily if the website doesn’t provide very short temporary cookies.
—————————————————————————–[/]

—[ 0x04: Difference between XSS and CSRF ]
Actually, what’s the real difference between XSS and CSRF? They look very similars!

As a matter of fact they’re quite similars, but there’s a core difference that makes the two vulnerabilities strictly opposed eachothers.

In the XSS vulnerabilities the USER trusts the WEBSITE’s integrity, and gets  tricked to give direct informations to the ATTACKER (with cookie grabbing of fake logins for example).

In the CSRF vulnerabilities is the WEBSITE that trusts in the USER’s requests and accomplish any kind of action that comes from his flagged authentication in order to get some advantages to the ATTACKER.

The Cross Site Request Forgery situation can be resumed with this graph:

                           trusted <-----flag-----.
	.----------.          .------.           .---|-----.
	| ATTACKER |__________| USER |___________| WEBSITE |
	`----------`  tricks  `------` (request) `---------`
	      |           \_ _ _ _ _ _ _ _/          |
	      |				             |
	      `--------------------------------------`

the website accomplishes the request

As we can see the situation is opposed to the XSS’ one, the website (trusting the authentication and the authorizations of the user) just accomplishes the request that are sent to him, which are obscured to the USER’s awareness.

The important point of this attack is that the request to the website is sent by the USER, not the ATTACKER: this makes the vulnerability more dangerous.
—————————————————————————–[/]

—[ 0x05: Get deep in CSRF ]
Okay, now that we got a general idea of what CSRF is, let’s try to get into some simple examples.

Assure that for example a user is subscribed into a website that provide some particular services, maybe which even schedule some money transactions: when the user logs in, the server will create a cookie or a session that flags the user as authed and authorized to access to his own private pages.

Assure also that the website is maybe a e-banking service and it provides an HTML form which perform money transactions, and the code will look like:

<!– scratch of a form –>
<form method=”POST” action=”sendmoney.php” name=”sendmoney”>
<div>How much: <input type=”text” name=”cash”></div>
<div>To: <input type=”text” name=”toname”></div>
<div>ABI: <input type=”text” name=”toabi”></div>
<div>CAB: <input type=”text” name=”tocab”></div>
<div>CIN: <input type=”text” name=”tocin”></div>
<div><input type=”submit” name=”submit” value=”Buy”></div>
</form>
<!– EOF –>

Through this form the user could transfer some money to the target bank account.
Ok, it’s really a stupid thing and quite impossible to be found right that, but it’s only to make you understand the thing more clearly :P don’t complain for that please!

Ok, when the user will submit the values of the form the script sendmoney.php will execute the query and make the e-banking system accomplish his request of transfer.
Maybe the script will look like:

/* sendmoney.php */
<?
session_start();
if(isset($_REQUEST['cash']))
$cash = $_REQUEST['cash'];
else
die(”Specify the amount of money”);
if(isset($_REQUEST['toname']))
$toname = $_REQUEST['toname'];
else
die(”Specify a recipient”);
if(isset($_REQUEST['toabi']))
$toabi = $_REQUEST['toabi'];
else
die(”Specify the ABI”);
if(isset($_REQUEST['tocab']))
$tocab = $_REQUEST['tocab'];
else
die(”Specify the CAB”);
if(isset($_REQUEST['tocin']))
$tocin = $_REQUEST['tocin'];
else
die(”Specify the CIN”);

// This function safely send the money to the target
send_money($cash, $toname, $toabi, $tocab, $tocin);

?>
/* EOF */

Consider that this script is well written and the send_money() sanitizes all the variables that are submitted to him, the transfer will be finally accomplished.

In this particular case the use of REQUEST global variable allows to an attacker to disfrut the GET method in order to trick the user and steal his money :)

If the user is authed in, as we previously said, an attacker could provide to the user a webpage or an image which will look like something like this:

<!– coolthing.html –>
<html>
<head><title>Cool Thing</title></head>
<body>
<img src=”http://bankhost.com/sendmoney.php?cash=ALL&toname=ME&toabi=
123456&tocab=123456&tocin=X”>
</body>
</html>
<!– EOF –>

Actually, if the user invited to visit this page is contemporary logged into the “bankhost.com” website, the image loaded will send an HTTP request to that website asking him to accomplish that transaction: the fact is that the transfer will be formerly commanded from the user himself.

Ok.. this is not really a good way for managing the transaction: the REQUEST global is not that safe, most probably the script sendmoney will use the POST variables instead, because they may think that it would be more secure.
Obviously it is not.

Consider that the coolthing.html file will look instead like:

<!– coolthing.html –>
<html>
<head>
<title>Cool Thing</title>
<script>
stealMoney() {
iframe = document.frames["stealmoney"];
iframe.document.steal.submit();
}
</head>
<body onload=”stealMoney()”>
<div><img src=”reallyc00landfunnypicture.jpg”></div>
<iframe name=”stealmoney” display=”none”>
<form method=”POST” name=” steal”
action=”http://bankhost.com/sendmoney.php”>
<input type=”hidden” name=”cash” value=”ALL”>
<input type=”hidden” name=”toname” value=”ME”>
<input type=”hidden” name=”toabi” value=”123456″>
<input type=”hidden” name=”tocab” value=”123456″>
<input type=”hidden” name=”tocin” value=”X”>
</form>
</iframe>
</body>
</html>
<!– EOF –>

As we can see this page’s appereance is composed only by the c00l picture loaded, but as an hidden action a crafted form in the iframe “stealMoney” will execute a request to the “bankhost.com” website, asking to the user’s session to transfer the money to the targeted infos :)

This is just a stupid example, but through this you can imagine what kind of  entity this vulnerability can take.
—————————————————————————–[/]

—[ 0x06: Attack Points ]
Let’s summarize then what happens creating a CSRF attack.
1- The attacker find a clueless user which is registered to a service vulnerable of CSRF
2- The attacker creates an html page which automatically send some requests to the vulnerable website
3- The victim logs into the website and get an opened session
4- The attacker provides the crafted html page to the victim
5- The victim visits that page
6- the HTTP request is sent and the malicious action accomplished :)

I think actually that it’s quite easy to understand how much dangerous this vulnerability could is for a smart and malicious attacker which basically knows how to move his attacks.
—————————————————————————–[/]

—[ 0x07: Prevention ]
Now that we understood how a CSRF attack is taken in action let’s try to analize how we could prevent and protect ourself from this kind of flaws.
In these months has been widely discussed how to prevent this kind of vulnerability but commonly without reaching any kind of fixed, stable and functional conclusion.
It has been talked about Unique Tokens, Captchas and others.. but i still think they still won’t be enough for this or simply can not be implemented smartly.

Awaiting for better results i suggest all of you to consider to ask to the user the password again at least on sensitive pages (like e-commerce forms and stuff), in order to be sure that the session cannot be hijacked (actually.. if the attacker doesn’t know the user password he couldn’t do anything dangerous and on the other side if he really know the password, he doesn’t require CSRF at all :P).

It’s really easy to implement this security misure, adding a new field in the
form:

<!– new scratch of the form –>
<form method=”POST” action=”sendmoney.php” name=”sendmoney”>
<div>How much: <input type=”text” name=”cash”></div>
<div>To: <input type=”text” name=”toname”></div>
<div>ABI: <input type=”text” name=”toabi”></div>
<div>CAB: <input type=”text” name=”tocab”></div>
<div>CIN: <input type=”text” name=”tocin”></div>
<div>Your passord: <input type=”password” name=”pass”></div>
<div><input type=”submit” name=”submit” value=”Buy”></div>
</form>
<!– EOF –>

And as it comes we’ll put a check like following in the ’sendmoney.php’ file:

/* scratch from sendmoney.php */
if(isset($_POST['pass']) && md5($_POST['pass']) == $mysql_row['pass']) {

} else {
die(”You must specify a correct password!”);
}
/* EOF */

In this way the CSRF attack attempts will be nullified if the attacker is not aknowledged of confidentials infos like the Password for example.

Other solutions like Unique Tokens based on PHP Sessions should be avoided because the attacker could bypass them.
—————————————————————————–[/]

—[ 0x08: Conclusions ]
Even this paper is actually finished: i hope as always that you enjoyed it at least as much as i enjoyed studying this theme.

Remember that you can always send feedback to me at  nexus @ playhack . net :)

Thanks to everybody out there and cheers to the italian scene


Que es Opcode?

June 25, 2008

En informática, un opcode (Operation Code) o Código de Operación, es la porción de una instrucción de lenguaje de máquina que especifica la operación a ser realizada. Su especificación y formato serán determinados por la arquitectura del conjunto de instrucciones (ISA) del componente de hardware de computador - normalmente un CPU, pero posiblemente una unidad más especializada. Una instrucción completa de lenguaje de máquina contiene un opcode y, opcionalmente, la especificación de unos o más operandos - sobre los que la operación debe actuar. Algunas operaciones tienen operandos implícitos, o de hecho ninguno. Algunas ISAs tiene instrucciones con campos definidos para los opcodes y operandos, mientras que otras (ej. la arquitectura Intel x86) tienen una estructura más complicada y de propósito específico.

Los operandos sobre los cuales los opcodes aplican pueden, dependiendo de la arquitectura del CPU, consistir de. registros, valores en memoria, valores almacenados en el stack, puertos de I/O, bus, etc. Las operaciones que un opcode puede especificar pueden incluir aritmética, copia de datos, operaciones lógicas, y control del programa.

Los opcodes también pueden ser encontrados en los bytecodes interpretados por un interpretador de código de byte (o la máquina virtual, en un sentido de ese término). En éstos, una arquitectura de conjunto de instrucciones es creada para ser interpretada por software en vez de un dispositivo de hardware. A menudo, los interpretadores de código de byte trabajan con tipos de datos y operaciones de más alto nivel, que el de un conjunto de instrucciones por hardware, pero son construidas a lo largo de líneas similares. Ejemplos incluyen la máquina virtual de Java (JVM) del lenguaje de programación Java, el código de byte usado en GNU Emacs para el código compilado de LISP, y muchos otros.

El lenguaje de máquina es tedioso y difícil para que los seres humanos lo programen directamente, así que si la abstracción dada por un lenguaje de programación de alto nivel no es deseada, un lenguaje ensamblador es usado. Aquí, son usadas las instrucciones mnemónicas que corresponden a las especificaciones del opcode y el operando de las instrucciones de lenguaje de máquina generadas. Esto da un mayor nivel de legibilidad y comprensibilidad, que trabajando directamente con operaciones de lenguaje de máquina, mientras que todavía da el control exacto del lenguaje de máquina generado. Un programa llamado ensamblador transforma el lenguaje ensamblador en código de máquina.


Test de Lenguaje C

June 19, 2008

#include <stdio.h>
int main()
{
int t = 4, s = t / 2;
if ( 5 > t && s = 2 )
……printf( “SI” );
else
……printf( “NO” );
return 0;
}

¿Cuál es VERDADERA?

A) La salida por pantalla es: NO
B) La condición no es correcta sintácticamente.
C) printf es una palabra reservada del lenguaje C.
D) A y C son CORRECTAS.
E) Ninguna de las anteriores.


C++ : Argumentos en Linea de Comandos

June 18, 2008

In C it is possible to accept command line arguments. Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. To use command line arguments in your program, you must first understand the full declaration of the main function, which previously has accepted no arguments. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.

The full declaration of main looks like this:

int main ( int argc, char *argv[] )

The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program.

The array of character pointers is the listing of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument. You can use each argv element just like a string, or use argv as a two dimensional array. argv[argc] is a null pointer.

How could this be used? Almost any program that wants its parameters to be set when it is executed would use this. One common use is to write a function that takes the name of a file and outputs the entire text of it onto the screen.

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    if ( argc != 2 ) /* argc should be 2 for correct execution */
    {
        /* We print argv[0] assuming it is the program name */
        printf( "usage: %s filename", argv[0] );
    }
    else
    {
        // We assume argv[1] is a filename to open
        FILE *file = fopen( argv[1], "r" );

        /* fopen returns 0, the NULL pointer, on failure */
        if ( file == 0 )
        {
            printf( "Could not open file\n" );
        }
        else
        {
            int x;
            /* read one character at a time from file, stopping at EOF, which
               indicates the end of the file.  Note that the idiom of "assign
               to a variable, check the value" used below works because
               the assignment statement evaluates to the value assigned. */
            while  ( ( x = fgetc( file ) ) != EOF )
            {
                printf( "%c", x );
            }
        }
        fclose( file );
    }
}

This program is fairly short, but it incorporates the full version of main and even performs a useful function. It first checks to ensure the user added the second argument, theoretically a file name. The program then checks to see if the file is valid by trying to open it. This is a standard operation, and if it results in the file being opened, the the return value of fopen will be a valid FILE*; otherwise, it will be 0, the NULL pointer. After that, we just execute a loop to print out one character at a time from the file. The code is self-explanatory, but is littered with comments; you should have no trouble understanding its operation this far into the tutorial.


Cross-Site Request Forgery en Plone 3.0.x

June 17, 2008

Se ha encontrado una vulnerabilidad en Plone 3.0.x que podría ser explotada por un atacante remoto para realizar ataques de cross-site request forgery (XSRF).

Plone es un Sistema de Gestión de Contenidos (CMS) de código abierto, basado en Zope y programado en Python. Dispone un entorno gráfico tipo web y permite múltiples funciones, llegando a utilizarse frecuentemente como CRM.

La vulnerabilidad está confirmada para las versiones 3.0.x y no afectaría a las versiones 3.1.x. La vulnerabilidad de cross-site request forgery (XSRF) o falsificación de peticiones entre sitios, se basa en explotar la confianza que un determinado sitio web tiene con un usuario. Un atacante remoto podría explotar este problema para cambiar ciertas configuraciones de seguridad de un usuario que se conecta con una sesión válida en Plone.

Se recomienda instalar el parche que solventa la vulnerabilidad para las versiones 3.0.x, disponible desde:
http://plone.org/products/plone-hotfix/releases/CVE-2008-0164/PloneHotfix-CVE-2008-0164.tar.gz

O instalar la versión 3.1.2 de plone, disponible desde:
http://plone.org/download

Más Información:

Plone Hotfix CVE-2008-0164
http://plone.org/products/plone-hotfix/releases/CVE-2008-0164


Syscalls en Linux

June 16, 2008

Via: Kernel-Labs

En este artículo vamos a estudiar cómo añadir una llamada al sistema, system call, a nuestro sistema operativo. Es una práctica bastante usada en las aproximaciones a la codificación del kernel Linux y bastante documentada, por ello, es obligado dar un repaso a todos estos conceptos. Entender el mecanismo de llamadas al sistema es una buena base para entender la filosofía de funcionamiento de un sistema Unix.
Syscalls
Los sistemas Unix, tradicionalmente proporcionan un interface para que las aplicaciones de espacio de usuario puedan comunicarse con el hardware. Esta interface son las system calls, conocidas en Linux simplemente como syscalls. Mediante estas llamadas, las aplicaciones podrán pedir al sistema operativo que realice tareas en su nombre. Por ejemplo, la función open() emitida por un proceso de usuario, estará indicando al kernel que abra algún fichero, el kernel que es el único con potestad para acceder al hardware (en este caso el disco), realizará la apertura del fichero que la aplicación le haya indicado en sus parámetros, es decir, el kernel se ejecutará en nombre del proceso de usuario, realizando la tarea que le ha sido pedida.

En realidad, las llamadas al sistema son casi el único punto de entrada que tienen los procesos de espacio de usuario al kernel. Es el principal mecanismo de comunicación de las aplicaciones con el kernel.
El puente API/syscall
Para que nuestra aplicación de espacio de usuario pueda emitir una syscall, es necesario poder realizar la llamada mediante un API que alguien nos proporcione. Este API lo proporciona la librería estándar de C de nuestro sistema, la libc o glibc en el caso de Linux. Una de las APIs más comunes del mundo Unix es la basada en el estándar POSIX. Este estándar aglutina un conjunto de estándares o recomendaciones del instituto IEEE, que intentan definir la base para la realización de sistemas operativos abiertos basados en Unix. Linux es considerado compatible POSIX, e intenta ajustarse al estándar SUSv3 (Single UNIX Specification Version 3 o UNIX 03) cuando es aplicable.

En la siguiente figura podemos ver la relación existente entre las aplicaciones, la librería de C y la llamada al kernel.

Read the rest of this entry »


Desbordamiento de Enteros

June 14, 2008

Revisión general del desbordamiento de enteros

Los sobreflujos de enteros, los subflujos y los sobreflujos aritmétivos de todos los tipos, en especial los errores de punto flotante, han sido un problema desde el comienzo de la programación de computadoras. Theo de Raddt, famoso por OpenBSD, afirma que los sobreflujos de enteros son la “próxima gran amenaza”.

El núcleo de este problema es que para casi cualquier formato binario que elijamos para representar números hay operaciones en que el resultado no corresponde con lo que se obtiene con lápiz y papel. Existen excepciones (algunos lenguajes implementan tipos de enteros de tamaño variable), pero no son comunes y vienen con cierta sobrecarga.

Otros lenguajes como Ada, implementan un tipo de entero de rango verificado, y si estos tipos se utilizan de manera consistente, reducen las posibilidades de problemas. He aquí un ejemplo:

type Age is new Integer range 0..200;

Los detalles del problema varían entre un lenguaje y otro. C y C++ tienen tipos de enteros verdaderos, y las personificaciones modernas de Visual Basic empaquetan todos los números en un tipo de punto flotante conocido como “Variant”, de modo que tiene la posibilidad de declarar un int, dividir 5 entre 4 y obtener 1 como resultado. En cambio, obtiene 1.25. Perl despliega su propio comportamiento distintivo; C# empeora el problema al exigir por lo general enteros con signo, pero luego rectifica y lo mejora creando una palabra clave “checkend”.

Lenguajes afectados

Todos los lenguajes comunes se ven afectados, pero los efectos difieren dependiendo de la manera en que el lenguaje manipula enteros internamente. C y C++ son quizás los más peligrosos, y es posible convertir un sobreflujo de entero en un desbordamiento del búfer y ejecución arbitraria de código, pero todos los lenguajes son propensos a negación de servicio y errores lógicos.

Explicación del Desbordamiento de enteros

Los efectos de errores de enteros van desde caídas del sistema y errores lógicos a escalamiento de privilegios y ejecución de código arbitrario. Una personificación actual del ataque depende en hacer que una aplicación cometa errores en la asiganación de código; al lograrlo, el atacante tiene la posibilidad de vulnerar un sobreflujo de heap. Si suele desarrollar en un lenguaje distinto de C/C++, tal vez piense que es inmune a sobreflujos de enteros, pero eso sería un equivocación. Los errores lógicos relacionados con el truncamientode enteros dieron como resultado un defecto en el sistema de archivos de red (Network File System, NFS), donde cualquier usuario tiene acceso a archivos como raiz.

Read the rest of this entry »


Las mujeres programan codigo mas considerado

June 14, 2008

Las mujeres programadoras escriben código más considerado frente al usuario que su contraparte masculina. “Los programadores varones escriben código aparentemente más complejo, únicamente para parecer más listos”, comenta destacada programadora.

A juicio de Emma McGrattan, una de las programadoras más prestigiosas de Silicon Valley, mujeres y hombres tienen enfoques totalmente distintos en la programación.

McGrattan, vicepresidenta de desarrollo de la empresa Ingress, indica que las mujeres son más sensibles y consideradas frente a las personas que usarán el código que ellas programan. Así, las mujeres procuran instalar comentarios de ayuda e instrucciones que explican por qué el código fue escrito de esa manera, y la forma en que lo hicieron.

“El código se transforma en una suerte de guía para otros, para facilitarles las cosas si desean agregar o cambiar algo posteriormente”, comentó McGrattan a Wall Street Journal.

Grattan indica que, por el contrario, los programadores varones no son tan considerados “e intentan demostrar lo inteligentes que son escribiendo códigos altamente ininteligibles. No dejan instrucciones y procuran deliberadamente que los elementos del código sean incomprensibles”, agrega McGrattan.

En un intento por hacer que el código de Ingres sea más amigable para el usuario, McGrattan ha desarrollado un nuevo estándar para la programación en la compañía. Así, ahora se exige que los programadores agregen comentarios detallados a su trabajo, donde se expliqué la función del código y el porqué. Asimismo, se pide a los desarrolladores elaborar una bitácora con la historia del código y los cambios que hayan sido aplicados. Las reglas se aplican a los empleados de Ingres y a los programadores de código abierto externos, que escriben código para la empresa.

McGrattan indica que en el 70 a 80 por ciento de los casos que observa código fuente puede determinar si ha sido escrito por un hombre o por una mujer.


Recursividad en C

June 13, 2008

# include”stdio.h”
int potencia (int,int);
void main ()
{
int b,e,x;
printf(”Introduce la base:n”);
scanf(”%d”,&b);
printf(”Introduce el exponente:n”);
scanf(”%d”,&e);
x=potencia(b,e);
printf(”la potencia es igual a %i”,x);
}
int potencia(int b,int e)
{
int pot=1;
if (e==0)
return 1;
else
{
pot=b*potencia(b,e-1);
return pot;
}
}


Historia de Java

June 11, 2008

Para apreciar el significado e importancia de Java, es muy importante conocer su lugar de origen y cuales fueron sus propósitos:

En Diciembre de 1990, Patrick Naughton, un empleado de la empresa Sun, reclutó a sus colegas James Gosling y Mike Sheridan para trabajar sobre un nuevo tema conocido como “El proyecto verde”. Este a su vez estaba auspiciado por la compañía “Sun founder Bill Joy” y tenía como objetivo principal crear un lenguaje de programación accesible, fácil de aprender y de usar, que fuera universal, y que estuviera basado en un ambiente C++ ya que había mucha frustración por la complejidad y las limitaciones de los lenguajes de programación existentes.

En abril de 1991, el equipo decidió introducir sistemas de software con aplicaciones para consumidores smart como plataforma de lanzamiento para su proyecto. James Gosling escribió el compilador original y lo denominó “Oak”, y con la ayuda de los otros miembros del equipo desarrollaron un decodificador que mas tarde se convertiría en lenguaje Java.

Para 1992, el equipo ya había desarrollado un sistema prototipo conocido como “*7″, que era una especie de cruce entre un asistente digital personalizado y un mecanismo inteligente de control remoto.

Por su parte el presidente de la compañía Sun, Scott McNealy, se dio cuenta en forma muy oportuna y estableció el Proyecto Verde como una subsidiaria de Sun. De 1993 a 1994, el equipo de Naughton se lanzó en busca de nuevas oportunidades en el mercado, mismas que se fueron dando mediante el sistema operativo base. La incipiente subsidiaria fracasó en sus intentos de ganar una oferta con Time-Warner, sin embargo el equipo concluyó que el mercado para consumidores electrónicos smart y las cajas Set-Up en particular, no eran del todo eficaces. La subsidiaria Proyecto Verde fue amortizada por la compañía Sun a mediados del 94’.

Afortunadamente, el cese del Proyecto Verde coincidió con el nacimiento del fenómeno mundial Web. Al examinar las dinámicas de Internet, lo realizado por el ex equipo verde se adecuaba a este nuevo ambiente ya que cumplía con los mismos requerimientos de las set-top box OS que estaban diseñadas con un código de plataforma independiente pero sin dejar de ser pequeñas y confiables.

Patrick Naugthon procedió a la construcción del lenguaje de programación Java que se accionaba con un browser prototipo, más tarde se le fueron incorporando algunas mejoras y el browser Hot Java fue dado a conocer al mundo en 1995.

Con el paso del tiempo el Hot Java se convirtió en un concepto práctico dentro del leguaje Java y demostró que podría proporcionar una forma segura multiplataforma para que el código pueda ser bajado y corrido del Host del World Wide Web y que de otra forma no son seguros.

Una de las características más atractivas del Hot Java fue su soporte para los “applets”, que son las partes del código Java que pueden ser cargadas mediante una red de trabajo para después ejecutarlo localmente y así lograr o alcanzar soluciones dinámicas en computación acordes al rápido crecimiento del ambiente Web.

Para dedicarse al desarrollo de productos basados en la tecnología Java, Sun formó la empresa Java Soft en enero de 1996, de esta forma de se dio continuidad al fortalecimiento del programa del lenguaje Java y así trabajar con terceras partes para crear aplicaciones, herramientas, sistemas de plataforma y servicios para aumentar las capacidades del lenguaje.

Durante ese mismo mes, Java Soft dio a conocer el Java Developmet Kit (JDK) 1.0, una rudimentaria colección de componentes básicos para ayudar a los usuarios de software a construir aplicaciones de Java. Dicha colección incluía el compilador Java, un visualizador de applets, un debugger prototipo y una máquina virtual Java(JVM), necesaria para correr programas basados en Java, también incluía paquetería básica de gráficos, sonido, animación y trabajo en red.

Asimismo el Netscape Comunications Inc, mostró las ventajas de Java y rápidamente se asoció con Java Soft para explotar su nueva tecnología. No pasó mucho tiempo antes de que Netscape Communications decidiera apoyar a los Java applets en Netscape Navigator 2.0. Este fue el factor clave que lanzó a Java a ser reconocido y famoso, y que a su vez forzó a otros vendedores para apoyar el soporte de applets en Java.

Como parte de su estrategia de crecimiento mundial y para favorecer la promoción de su nueva tecnología, Java Soft otorgó permisos a otras compañías para que pudieran tener acceso al código fuente de Java y al mismo tiempo mejorar sus navegadores , dicha licencia también les permitía crear herramientas de desarrollo para programación Java y los facultaba para acondicionar Máquinas Virtuales Java (JVM), a varios sistemas operativos.

Muy pronto las licencias o permisos contemplaban a prestigiadas firmas como IBM, Microsoft, Symantec, Silicon Graphics, Oracle, Toshiba y por supuesto Novell.

Desde su aparición, Java se ha ganado una impresionante cantidad de apoyo. Virtualmente cada vendedor importante de software ha obtenido autorización de Java y ahora ha sido incorporado en los principales sistemas operativos base de PC’s de escritorio hasta estaciones de trabajo UNIX.

Los applets Java (basados en JDK 1.02) son apoyados por los dos más populares navegadores web (Netscape Navigator 3.0 y Microsoft Internet Explorer 3.0). I.B.M./Lotus, Computer Asociates, Symantec, Informix, Oracle, Sybase y otras poderosas empresas de software están construyendo Software 100% puro JAVA, por ejemplo el Corel Office que actualmente está en versión Beta.

Un gran número de nuevas empresas ya están preparadas para recibir a la Ola Java o para ingresar a los Mercados de software basados en Java, en algunos casos como “Marimba´s Castanet” se han concebido desde un principio con bases de tecnología Java para Internet y han sido autorizados bajo licencia de Netscape para poner al corriente “netcast”, un producto informativo para PC’s de escritorio.

Los nuevos proyectos de Java son co-patrocinados por cientos de millones de dólares en capital disponible de recursos tales como la Fundación Java, un fondo común de capital formado el verano pasado por 11 compañías, incluyendo Cisco Systems, IBM, Netscape y Oracle.

Los Colegios y Universidades alrededor del mundo están adoptando Java como un lenguaje universal y de enseñanza indispensable, hoy en día existen más de 150 libros en Java que se están imprimiendo en este momento.

En un reciente estudio se encontró que el 60% de los empresarios están usando Java y el 40% expresaron que Java representa la solución estratégica que estaban buscando para sus negocios..

Para darse una idea de la rápida aceptación que tiene Java en el mundo, tenemos el ejemplo de las conferencias “Java Soft Java One” en San Francisco, el primer Java One fue celebrado en abril de 1996 y atrajo a 5000 usuarios, un año después, en la segunda conferencia Java One albergó a 10,000 usuarios, asistentes. Java Soft estima que el número actual de usuarios Java llega a 400 mil y sigue creciendo. Java también está ganando aceptación en el área empresarial, se ha estimado que actualmente las compañías de hoy que cuentan con más de 5000 empleados, una tercera parte están usando Java.


Top Ten Errors Java Programmers Make

June 11, 2008

Actualmente comienzo a aprender algo de Java asi que me puse a buscar informacion y me encontre con este interesante articulo sobre el top ten de los errores mas frecuentes de los programadores en Java. Me parece que es bueno de vez en cuando tener unos puntos de referencia como este.

Whether you program regularly in Java, and know it like the back of your hand, or whether you’re new to the language or a casual programmer, you’ll make mistakes. It’s natural, it’s human, and guess what? You’ll more than likely make the same mistakes that others do, over and over again. Here’s my top ten list of errors that we all seem to make at one time or another, how to spot them, and how to fix them.
10. Accessing non-static member variables from static methods (such as main)

Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static - meaning that we don’t need to create an instance of the class to invoke the main method. For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-

MyApplication.main ( command_line_args );

This means, however, that there isn’t an instance of MyApplication - it doesn’t have any member variables to access! Take for example the following application, which will generate a compiler error message.

public class StaticDemo
{
public String my_member_variable = “somedata”;

public static void main (String args[])
{
// Access a non-static member from static method
System.out.println (”This generates a compiler error” +
my_member_variable );
}
}

If you want to access its member variables from a non-static method (like main), you must create an instance of the object. Here’s a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.

public class NonStaticDemo
{
public String my_member_variable = “somedata”;

public static void main (String args[])
{
NonStaticDemo demo = new NonStaticDemo();

// Access member variable of demo
System.out.println (”This WON’T generate an error” +
demo.my_member_variable );
}
}

9. Mistyping the name of a method when overriding

Overriding allows programmers to replace a method’s implementation with new code. Overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you’ll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to mistype the method name. If you mistype the name, you’re no longer overriding a method - you’re creating an entirely new method, but with the same parameter and return type.

public class MyWindowListener extends WindowAdapter {
// This should be WindowClosed
public void WindowClose(WindowEvent e) {
// Exit when user closes window
System.exit(0);
}
});

Compilers won’t pick up on this one, and the problem can be quite frustrating to detect. In the past, I’ve looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn’t being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn’t being called, then it’s likely you’ve mistyped the name.
8. Comparison assignment ( = rather than == )

This is an easy error to make. If you’re used other languages before, such as Pascal, you’ll realize just how poor a choice this was by the language’s designers. In Pascal, for example, we use the := operator for assignment, and leave = for comparison. This looks like a throwback to C/C++, from which Java draws its roots.

Fortunately, even if you don’t spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : “Can’t convert xxx to boolean”, where xxx is a Java type that you’re assigning instead of comparing.
7. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Here’s the correct way to compare two strings.

String abc = “abc”; String def = “def”;

// Bad way
if ( (abc + def) == “abcdef” )
{
……
}

// Good way
if ( (abc + def).equals(”abcdef”) )
{
…..
}

6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you’re passing by value, and when you’re passing by reference.

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the “real” variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.

When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type. So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object’s member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.

On a side note, since String contains no methods to modify its contents, you might as well be passing by value.
5. Writing blank exception handlers

I know it’s very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and haven’t written any error messages, it becomes almost impossible to find out the cause of the error. Even the simplest exception handler can be of benefit. For example, put a try { .. } catch Exception around your code, to catch ANY type of exception, and print out the message. You don’t need to write a custom handler for every exception (though this is still good programming practice). Don’t ever leave it blank, or you won’t know what’s happening.

For example

public static void main(String args[])
{
try {
// Your code goes here..
}
catch (Exception e)
{
System.out.println (”Err - ” + e );
}
}

4. Forgetting that Java is zero-indexed

If you’ve come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element’s index is actually 0. Confused? Let’s look at a quick example.

// Create an array of three strings
String[] strArray = new String[3];

// First element’s index is actually 0
strArray[0] = “First string”;

// Second element’s index is actually 1
strArray[1] = “Second string”;

// Final element’s index is actually 2
strArray[2] = “Third and final string”;

In this example, we have an array of three strings, but to access elements of the array we actually subtract one. Now, if we were to try and access strArray[3], we’d be accessing the fourth element. This will case an ArrayOutOfBoundsException to be thrown - the most obvious sign of forgetting the zero-indexing rule.

Other areas where zero-indexing can get you into trouble is with strings. Suppose you wanted to get a character at a particular offset within a string. Using the String.charAt(int) function you can look this information up - but under Java, the String class is also zero-indexed. That means than the first character is at offset 0, and second at offset 1. You can run into some very frustrating problems unless you are aware of this - particularly if you write applications with heavy string processing. You can be working on the wrong character, and also throw exceptions at run-time. Just like the ArrayOutOfBoundsException, there is a string equivalent. Accessing beyond the bounds of a String will cause a StringIndexOutOfBoundsException to be thrown, as demonstrated by this example.

public class StrDemo
{
public static void main (String args[])
{
String abc = “abc”;

System.out.println (”Char at offset 0 : ” + abc.charAt(0) );
System.out.println (”Char at offset 1 : ” + abc.charAt(1) );
System.out.println (”Char at offset 2 : ” + abc.charAt(2) );

// This line should throw a StringIndexOutOfBoundsException
System.out.println (”Char at offset 3 : ” + abc.charAt(3) );
}
}

Note too, that zero-indexing doesn’t just apply to arrays, or to Strings. Other parts of Java are also indexed, but not always consistently. The java.util.Date, and java.util.Calendar classes start their months with 0, but days start normally with 1. This problem is demonstrated by the following application.

import java.util.Date;
import java.util.Calendar;

public class ZeroIndexedDate
{
public static void main (String args[])
{
// Get today’s date
Date today = new Date();

// Print return value of getMonth
System.out.println (”Date.getMonth() returns : ” +
today.getMonth());

// Get today’s date using a Calendar
Calendar rightNow = Calendar.getInstance();

// Print return value of get ( Calendar.MONTH )
System.out.println (”Calendar.get (month) returns : ” +
rightNow.get ( Calendar.MONTH ));

}
}

Zero-indexing is only a problem if you don’t realize that its occurring. If you think you’re running into a problem, always consult your API documentation.
3. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy’s law holding, the probability) that two threads will access or modify the same data at the same time. Don’t be fooled into thinking that such problems won’t occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already, right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
{
count = amount;
}

public synchronized int getCount()
{
return count;
}
}

2. Capitalization errors

This is one of the most frequent errors that we all make. It’s so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don’t spot the lack of capitalization.

While there’s no silver bullet for detecting this error, you can easily train yourself to make less of them. There’s a very simple trick you can learn :-

* all methods and member variables in the Java API begin with lowercase letters
* all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

If you use this pattern for all of your member variables and classes, and then make a conscious effort to get it right, you can gradually reduce the number of mistakes you’ll make. It may take a while, but it can save some serious head scratching in the future.
(drum roll)
And the number one error that Java programmers make !!!!!

1. Null pointers!

Null pointers are one of the most common errors that Java programmers make. Compilers can’t check this one for you - it will only surface at runtime, and if you don’t discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven’t initialized an object, or you haven’t checked the return value of a function.

Many functions return null to indicate an error condition - but unless you check your return values, you’ll never know what’s happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!

Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.

public static void main(String args[])
{
// Accept up to 3 parameters
String[] list = new String[3];

int index = 0;

while ( (index < args.length) && ( index < 3 ) )
{
list[index++] = args[index];
}

// Check all the parameters
for (int i = 0; i < list.length; i++)
{
if (list[i].equals “-help”)
{
// ………
}
else
if (list[i].equals “-cp”)
{
// ………
}
// else …..
}
}

This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you’ll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won’t. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

Fuente


Virus cifra archivos a 1024 bits

June 10, 2008

La compañía de seguridad informática Kaspersky Labs advierte contra un virus extorsionador actualizado. El virus GpCode cifra los archivos del PC impidiendo su lectura. Luego notifica al afectado que para obtener la clave usada para cifrar el material es necesario contactar a una dirección anónima de correo electrónico. La clave usada es de RSA de 1.024 bits y actualmente es imposible de romper.

El virus en cuestión cifra los archivos doc, txt, pdf, jpg y ccp. La raíz de los archivos intervenidos es modificada a ._crypt y son subidas a un archivo de texto donde se indica que es necesario comprar una clave para recuperar el acceso a los archivos.

Anteriormente, Kaspersky ha logrado vulnerar el sistema de cifrado de una versión anterior de GpCode, con clave de 660 bits. Sin embargo, los desconocidos autores del virus han actualizado el código, de forma que emplea el invulnerable algoritmo de 1.024 bits.

Los expertos de Kaspersky están abocados a detectar debilidades en el código del virus, con el fin de recuperar los archivos sin que sea necesario usar la clave. Kaspersky sugiere a los usuarios afectados por el virus contactarles de inmediato y no reiniciar ni apagar el PC infectado.