lunes, 23 de febrero de 2009

Evitando abuso en sitios web

Alternativas para evitar abuso de los portales

Uno de los principales riesgos en la operación de nuestros portales es su posible abuso por parte de terceros que con el fin de hacerse a la base de datos que los alimentan, están en capacidad de ejecutar todas las consultas que a bien tengan, tanto manual como automáticamente.

Los portales son muy vulnerables a estos abusos (que no se pueden catalogar realmente como “ataques”) dado que la naturaleza del negocio implica que todas las consultas estén abiertas a todos los públicos y no con menos importancia, a los motores de búsqueda; de manera que no existen mecanismos de autenticación que impidan por ejemplo el acceso al sitio por medio de robots o programas que extraen automáticamente el contenido de nuestros sitios además existen efectos colaterales como disminución del ancho de banda y de velocidad de proceso en los sitios.
Existen básicamente dos tipos de acciones que podrían ayudar a mitigar este riesgo. El primer tipo comprende las acciones ejecutadas a nivel de la infraestructura de la aplicación. El segundo tipo consiste en las acciones ejecutadas a nivel de desarrollos adicionales en la aplicación como tal.

Infraestructura
Existen servidores de seguridad que reciben todas las peticiones de los clientes antes de que estas lleguen a la aplicación como tal. Esta herramientas se instalan al frente de los servidores web. Y ayudan a través de los siguientes mecanismos:

Cookies
Las cookies estarían almacenando la cantidad de requests que está haciendo cada cliente en una unidad de tiempo dada. Esto requiere sin embargo que se exija a todos los clientes el uso de cookies, cosa poco ideal, pues hoy en día existen muchos usuarios que desactivan estas cookies en sus browsers.

Javascript
El uso de javascript permite generar rutinas que los robots no podrían seguir, de manera que el acceso quedaría restringido a estos entes automatizados. La gran contra que tiene este enfoque, es que puede requerir procesos de considerable costos en el servidor. Además que se le estaría restringiendo el uso también a motores de búsqueda como google que usan robots para obtener información de los sitios.


Aplicación
A nivel de aplicación el conjunto de acciones posibles es más diverso. Se trata de rutinas destinadas a detectar accesos irregulares a la aplicación. Estas pueden ser provistas como productos terminados ya hechas por terceros, o como desarrollos nuevos dentro de la aplicación.

Delay
Existen herramientas como ISTools de Peter Blum, que basadas en un patrón de IP (esto puede ser contraproducente en el caso de que las ips reales estén siendo reemplazadas por las ips de los ISP) detectan los accesos irregulares y generan retardos en las respuestas, advertencias y finalmente denegación del servicio a los supuestos atacantes. Un caso favorable es que en algunas ocasiones los ISP mantienen la ip de sus clientes y la reenvían como una variable HTTP que puede ser consultada. Pero esto no ocurre siempre.

Javascript y Cookies
Ambos mecanismos funcionan con desarrollos de productos de igual forma a la que fue descrita en el apartado de infraestructura.

Listado de Robots
Herramientas de terceros permiten consultar un IP dada y verificar si ha sido tildada como un robot para en ese caso tomar acciones al respecto.

Cómo obtener la solución al problema
Para generar una solución se han de tener en cuenta los siguientes puntos:
  1. Como se observa luego de la investigación y entrevista con el proveedor de infraestructura, hoy en día no hay una solución ad-hoc que abarque todo el problema sobretodo sin efectos colaterales.
  2. Para generar una solución es muy necesario comenzar por definir unas políticas de detección de abuso que permitan establecer los parámetros para las herramientas que se usaran/construirán
  3. No es posible obligar la autenticación en los portales luego no hay manejo de sesión
  4. Existen ISPs que direccionan los requerimientos con una IP única
  5. Existen usuarios que no permiten el uso de cookies en sus máquinas
Teniendo en cuenta lo anterior, se puede sugerir implementar una solución compuesta tal como se describe a continuación:

  1. Definir la política de uso abusivo (Esto implica declarar cuándo se considera que se está extrayendo información del sitio de manera inescrupulosa; por ejemplo, que un mismo usuario visite más de 50 páginas de resultados de una misma búsqueda, o que realice más de 20 búsquedas distintas en un determinado lapso de tiempo)
  2. Definir las acciones a tomar luego de la violación de la política. (Redireccionar a un captcha, denegar el servicio, retardar el servicio, etc.)
  3. Proveer un mecanismo que permita avisar acerca de la violación de la política de acceso. Dependiendo de lo elaborado de la política, esto puede ser ejecutado desde la infraestructura o de la aplicación. Una política sencilla como solo contar el número de requests de una ip dada se puede implementar en la infraestructura. Pero ya hemos visto que esto no es conveniente dadas las condiciones de negocio actuales. Una política algo más completa como la descrita como ejemplo en el numeral 1, requiere de un a implementación en el lado de la aplicación.
  4. Implementar e integrar los puntos anteriores de manera que cuando el mecanismo de advertencia avise acerca de un posible abuso de acuerdo a las políticas definidas, se tomen las acciones pertinentes.

Recomendaciones acerca de la política de abuso


Un acceso abusivo siempre puede ser detectado cuando desde una misma IP son hechos muchos requests. Pero esto mismo puede suceder con el caso de los ISP que tienen una sola ip de salida. Para evitar tachar incorrectamente a los ISP es necesario verificar el tipo de requests que se están haciendo desde una ip sospechosa. En general las consultas sobre los sitios no abarcan más de 10 páginas de resultados de un mismo tema. También de acuerdo a las estadísticas se puede establecer un límite para distintas búsquedas en un tiempo dado por una ip dada; por ejemplo más de 100 búsquedas distintas en 10 minutos indicarían un comportamiento malicioso.

Entonces ante una violación a la política establecida anteriormente se garantizaría que no se cae en el falso positivo del ISP así que ante este comportamiento sospechoso se podría iniciar con buscar la IP en una base de datos provista por un tercero en la que están registrados los robots en la actualidad. Si este filtro pasa, se continúa con la verificación de si se trata de un robot autorizado como el de google o yahoo; esto se logra a través de un DNS lookup reverso. Aquí entonces si no pasa la validación, se procederá con la acción correctiva.

Como inconveniente a esta solución, se cita la complejidad de su desarrollo, ya que requiere hacerse del lado de la aplicación que al no tener manejo de sesión, requeriría una implementación con almacenamiento en base de datos tal como se hace con las estadísticas actualmente.

sábado, 13 de septiembre de 2008

LinQ to SQL DOES have much practical use

Nowadays, big data based projects have to be accessible for multiple clients. Those clients are very prone to have much different needs on that data. So if the decision of having all the business logic required by all the clients inside the DB in stored procedures is taken, the result will be hundreds of SPs, very difficult to manage, and to create when the bussines logic comprise some complexity. In this case, just looking the "no-compilation required" advantage offered by the stored procedures is not enough. The current software industry requires connectivity in first place. Re-use and extension of basic functionality.

Stored Procedures still being a good choice though, but let them for that basic functionality you need to provide. And for clients, now there is nothing better than LinQ to SQL. Just imagine a stored procedure giving you some data you'll need to make complex calculations with, using all the power and ease offered by the .NET Framework and that you can play with all of these just using C# (goodbye to text commands!!!), everything strong typed and "intellisensed".
So I think saying "LinQ to SQL may not have much practical use", is product of a very narrow point of view. You need to have the big picture with all the new software projects style before making such asseveration.

martes, 12 de agosto de 2008

Sql Server 2008. Qué hay de nuevo?

Algo breve:

Asignación de variables en la misma línea donde se declaran
Asignación compuesta a través de operadores ( declare @n = 10 set @n += 1 'n = 11 )
Constructores de Fila mejorados (Por fin!!! - sirven por ejemplo para datos de pruebas)
Merge de Tablas (Actualiza los registros conicidentes, o agrega los nuevos)
Un tipo Tabla: Para poder ser pasado a stored procedures, etc.

martes, 22 de julio de 2008

Text Duplicates in IE6

Internet Explorer 6 has a puzzling bug involving multiple floated elements; text characters from the last of the floated elements are sometimes duplicated below the last float. This bug is a real headbanger because there seems to be nothing triggering it. However, by now everyone should know that IE needs no excuse to misbehave.

The direct cause is nothing more than ordinary HTML comments, such as, , sandwiched between floats that come in sequence. Apparently, the comments are hard for IE to digest when they occupy those positions, resulting in a kind of "screen diarrhea". HTML comments inside the floats do not cause the bug, nor do comments before or after the float series. Only comments residing between floats cause the bug.

The effect seen is that some of the last characters from the last floated element of the series are repeated outside and below that floated element. The first sandwiched comment does nothing unusual, but two comments cause the last two characters in that last float to repeat. Each additional comment makes two more characters join the party. It doesn't matter which pair of floats straddle the comments. In fact the two triggering comments may follow different floats as long as they have floats both before and after them.


From: http://www.positioniseverything.net/explorer/dup-characters.html

lunes, 23 de junio de 2008

HOWTO: Allow file downloads (including .exe) on IIS 6.0

Variations of this question are asked of IIS 6 all the time. However, the answer is no different than for any other version of IIS other than the fact that IIS 6 gives you a distinct error code to troubleshoot. What is not clear to me is why users think that the newly introduced Web Service Extension concept has something to do with this misconfiguration... I hope someone can give me some rationale.

Question:
Hello,

What is the correct method to allow .exe files to be downloaded or run from a web site on an IIS 6.0 server?

I am currently receiving a 404.2 error message in my browser when I try to open/download the executable files, and I am not sure which Web Service Extensions configuration changes must be made to allow this.

Thanks in advance,

Answer:
Given the current phrasing of your question, there is no correct method. Downloading a .exe file is NOT the same as run from a website, as I will describe below. I'll give a short answer and then a more detailed answer.

Short Answer
Your error message indicates that you have "Scripts and Executables" enabled, so IIS is trying to execute the .exe file on the web server, and since the .exe is not allowed by any defined Web Service Extension, a 404.2 results. The corrective action depends on what you want to do.

If you want to allow .exe files to be downloaded as-is to the browser, then you must NOT have "Scripts and Executables" as Execute Permissions.
If you want to execute the .exe file on the server to generate a response that is sent to the browser (possibly interpreted as a download), then you MUST have "Scripts and Executables" as Execute Permissions, and you must enable a Web Service Extension for that .exe file.
Details
Whenever the user makes the browser request a resource like "http://server/myapp.exe", users usually want one of the following actions to happen:

Return the file contents of myapp.exe as-is to the browser (aka file download)
Execute myapp.exe on the web server to generate a dynamic response (aka execute CGI script)
Now, the web server controls which action should happen, and on IIS, this is controlled by the "Execute Permissions" property of the virtual directory containing the .exe file. If the permission is set to "Scripts and Executables", then IIS will do action #2. Otherwise, it will do action #1.

Prior to IIS 6.0, there were no further security checks against either action. On IIS 6.0, there is one additional security check, depending on the action:

For action #1, the file resource's extension (.exe in this case) must have a defined MIME Type or else a 404.3 occurs. .exe has a MIME Type of application/octet-stream by default, so file download should just work.
For action #2, there must be an enabled Web Service Extension for the full path to the .exe resource to allow IIS to execute it to generate a HTTP response or else a 404.2 occurs. For securety reasons, IIS 6 does not allow any resource to execute by default unless otherwise configured/allowed in Web Service Extension.



From: http://blogs.msdn.com/david.wang/archive/2005/07/11/Allow_file_downloads_on_IIS_6.aspx

jueves, 19 de junio de 2008

Detallitos de CSS en Themes de ASP.NET

Los descubrimientos descritos a continuación, surgieron de mi necesidad de cargar CSS dinámicamente si estar creando mumerosos temas dentro de una aplicación WEB ASP.NET.

En primera instancia: Toda página que referencie un tema, SIEMPRE cargará absolutamente todos los CSS incluidos en el mismo, independientemente de que en realidad los necesite, y del nivel de anidamiento en el que se encuentren ubicados. Poco eficiente no es así?

Como se sabe, los CSS finalmente son Links referenciados en el HEAD de la página que está referenciándolos. Entonces es cuestión de escribir dinámicamente allí la ruta del CSS que se desea cargar y listo.

Lo anterior se logra metiendo un ASP.NET literal control dentro del HEAD, y en el load de la página ajustarlo con el valor que se desea.

Y listo!!!
Verificando con Firebug, se observa que a pesar de que existan varios CSS en la misma ruta de aquel que está siendo referenciado, solo el referenciado se descarga.

Ventajas?
Tener organizados varios CSS y no solo uno gigantesco con todo.
En cuanto a ancho de banda, si los CSS se dejan dentro de temas, por más separados que estén si son cargados por medio de referencia al tema desde la página, siempre bajan todos la primera vez que se llamen (luego quedan en el caché y no vuelven a descargarse si no se borra el caché o si no cambian en el server).

Si se desea optimizar el tiempo de descarga, entonces es mejor no usar Themes para cargar los estilos, sino que estos se carguen independientemente usando el modelo de HEAD descrito anteriormente.

lunes, 7 de abril de 2008

Table vs. DIV

I have a little story to tell about the webmaster who used a table with DIVs and the webmaster who didn't. The webmaster who didn't use a table had the higher paying job, a big house, a nice car, and a hot wife because he got all the good jobs for his tableless designs. The webmaster who used tables only to insert his DIVs was considered a second-rate bum and many believed he didn't even know how to position his DIVs. He made very little money. He lived in a rundown apartment. He had no car, and he had no wife.Then oneday the webmaster who had a classy job and the ever-so-popular tableless designs one day was sitting at his desk smoking a cigar talking on his cell phone about where to meet his buddies for lunch when his boss came running in all excited and out of breath."We just got a whole bunch of affiliate partners that want to place ads on our pages so they can make money and we can make commissions! We want an entire column added to the right side of every page!"Now the site had been around for several years and there were thousands of pages of content to add this column to, and the pages were all written in DIVs. So, the webmaster gasped and dropped his phone as the cigar fell from his mouth and he said, "Well, that is going to take some time, I got to place new DIV tags on every page to add one column of ads and that is no easy task!"The boss lamented this news, because not only would that mean he would not be making money off of his affiliates until the job was done, but he would have to hire someone else to assist the webmaster with his work until the site was updated. So, trying to save some money and not wanting to take a lot of time to hire someone on a contract, he hired the poor unsuccessful webmaster who always used tables to position his DIVs. The poor and destitude webmaster reluctantly decided he had no choice but to accept the tedious task, because he needed the money. So, for nearly a month he labored on inserting the appropriate DIVs on each page, copying and pasting many times into each page. When it was all said and done he went to the boss, and he shook his head and said, "You know it took a lot of copying and pasting to insert all them new DIV tags...If the site had been designed with a table I would have only had to copy and paste once into each page to insert the new column. You would have made a lot more money instead of having to hire someone else on, and it would have saved me from a lot of headaches going vertigo looking at code. I hope you never have to add a column again, for your sake and mine."The boss shook his head, and stopped the man before he could go. "Wait!" he said. "I could have been making tens of thousands of dollars a day all this time if you had done my site with tables?"The tired and frustrated impoverished webmaster nodded with a grim expression, and the boss threw up his hands and rolled his eyes. Racing out of his office, he motioned for the poor webmaster to follow after him as he charged into the rich webmaster's office. The rich webmaster was polishing his W3C Validation pin on his suit jacket as they entered and he smiled saying, "So, did the columns get added to all the pages?""Yes!" shouted the boss, "but you're fired! I got me a new webmaster right here who is going to make sure I never lose money adding a column of ads again!"Now, the poor webmaster is no longer poor, and the rich webmaster is no longer rich. He lost his big house. He lost his nice car. He lost his hot wife, because she only loved him for his money, and he is in the psyche ward for going nuts and breaking computers at a department store.

Like it is said: It all depends on the viewpoint. It exists another technique yet. The CSS positioning. It have its advantages and drawbacks too. So please try using all of this techiniques and acquire the experience. Then you will know which technique will be the best choice.