Cyril Maithily Gupta's Blog » 2008 » June

Archive for June, 2008

Protect your database against SQL Injection

Monday, June 30th, 2008

When you open a website on the Internet, you issue an open invitation to everybody to come in and have a look. Some of the visitors are nice who appreciate what you do, but some might not be so pleased. There can be hackers, dirty competition, or plain jealous folk who would be too happy to take you down, and sometimes it’s easier than you imagine.

One of the most common attacks on Internet websites is through SQL Injection. In this technique, hackers try to modify or delete your SQL database by feeding your website evil SQL command masquerading as valid SQL code. It’s sometimes easier to do this then you think. If you’re using querystrings, or asking your users to put in input, it can be potentially used against you.

Here’s a scenario: You’ve got a great online products catalog, and you let users search through it. You’ve got a box on your main page in which users can type the product names. You’re using a standard sql query to conduct a search. Something that looks like this: -

SELECT * FROM Products WHERE Prod_Name = ‘MyProd’

Instead of typing in the product name, a hacker can just add some malicious sql code, and can potentially modify your data. This is SQL Injection. Injecting SQL code where you expect other values and taking you out by surprise. It’s a sneaky attack of the lowest form.

So how can you protect your website against the spineless crud?

There are many solutions, and you should have multiple levels of protection to maximise your security.

1. Limit input as much as possible. Try to use combo boxes, or lists instead of text boxes whenever you can.

2. Put in an upper limit on the number of characters. If you’re expecting an input of only 20 chars, don’t accept 200 chars.

3. Validate the input. If you’re expecting only numbers, don’t accept alphanumeric input. Similarly, if you don’t need things like apostrophes, asterisks, (can be used dangerously in sql code), don’t accept them, or remove them.

4. Monitor for dangerous input. If you’re particularly susceptible, or suspect that someone is out to hurt your website, search your input for dangerous keywords like DELETE, UPDATE, etc.

5. Don’t make your database field obvious. Never, never show your database field in your query string. I.e. avoid having a querystring like this: ‘http://www.mywebsite?ProductID=23′. Don’t name your query string variable ‘ProductID’ in the case above, cause it’s obvious that’s your database field name as well.

6. If you’re using MS Sql, you’re luckier, cause Microsoft has some in-built security in MS Sql that prevents unauthorised sql code from running when it suspects there’s something wrong.

7. Must use SQL Parameters. This is probably the most important tip I can give you. Don’t just attach your argument variables at the end of a literal sql string. I know it needs more lines, but use SQL parameters anyway. This makes sure that the input conforms to your required data type, and prevents malicious code.

That’s what I can think of for now. If you can add anything, do suggest.

Can we harness the nature in a non-obtrusive manner?

Monday, June 30th, 2008

At the moment, almost all of our technology is destructive. Our manufacturing processes are mechanical, that create products by distorting what was formed by nature. We make overuse of things like plastics, concrete, fossil fuels, and chemicals, introducing materials into the environment that it wasn’t ready for.

Evolution equips the environment to cope with all possible slow changes. That’s why every material that’s a product of nature if bio-degradable, be it bones, skin, plant tissue or any other product. Human beings created materials that nature had never seen earlier, and that’s why it wasn’t prepared for their sudden introduction. There’re simply no bacteria or agents that can degrade the chemicals and materials we’re releasing.

Maybe some hundred, or thousand years down the line a new strain of micro-organisms will appear that can degrade the plastics and other material we’ve introduced, but by then earth would already be overrun, too polluted to turn back into the largely gentle nurturer of life that it’s now.

That’s why it’s important to find ways to limit the eco-logical impact of our activities. Ingenuity, and bio-technology can make that happen. Why do we live in houses made of concrete when concepts such as the earth houses have already been proven. Maybe if we put bio-technology to work, we can develop newer bio material as the construction material for our houses. Imagine if you had a that had walls made of a tree, which would only need water, to maintain itself. This might seem far-fetched now, but can become a reality.

We need micro-solutions to our problems. Solutions that are tailor made to each family and home’s need instead of a large-scale, fit-all solution. Take power generation for example. Right now our focus is to build bigger and bigger powerplants, nuclear power, and huge arrays of solar power dishes. Would it not be better to approach the problem from the other end. To promote use of solar power cells, personal windmills, and other sources of alternative power at the level of a home. Even if it does not remove the need of an external power source, it can definitely reduce the load on the power-plant. Then why aren’t we investing more on developing small scale solutions instead of large-scale ones?

The answer is, money. Large companies don’t want to decentralize solutions, because it would take money away from them. Instead they want you to pay regular utility bills to the huge power plant they run.

But this simply can’t be sustained. Like centralisation at the dawn of the factory age, de-centralization is a trend that cannot be reversed in the information age. It’s the only way left for humanity to continue growing and surviving.

Coming back to the main topic. How is it possible to limit our ecological footprint and still have sustained growth? By putting bio-technology to work instead of machines. Some days ago I day-dreamed of a plant that would use a process similar to photo-synthesis, and generate electric current. Maybe that won’t happen soon, but it would be great if we could find a way to generate current without destroying a plant.


Have a look at this technology for example. They’ve put in things that look like buoys at the bottom of the ocean. These buoys move due to the ocean current and generate electricity. It’s a perfectly non-destructive source of energy, and no sea organisms are harmed.

It’s technology like this we need.

FOB : Midas World By Frederik Pohl

Sunday, June 29th, 2008
Midas world by Frederik Pohl

Midas world by Frederik Pohl

Pohl’s Midas World is not a novel, although it says on the cover. It’s a collection of several inter-connected short stories that have a common foundation – an endless source of energy that causes a slow degeneration of human society, and rise of robots. The stories are a chronological documentation of the events, marking how the society evolves as humanity first gives birth to robots, and then lets them take over.

The robots of Midas World are evidently inspired by Asimov’s robots in that they too can’t, or don’t wish to harm humanity. Robots are mostly moral, and often more intelligent and sensible than human beings around them. Unfortunately there’s no Daneel R. Olivaw around to prevent the degeneration of human society.

The saga starts with the discovery of practical nuclear fusion by Alfie Amadeus who later realizes that his discover is mankind’s doom, but is too powerless to prevent it from happening. The connection between Amadeus’ discovery and the robots is a bit vague as Amadeus did not make the robots, and so wasn’t directly responsible for what happened.

At first robots are created to do the menial jobs for mankind, but slowly they take over everything that man did himself, including consume, create art, research, and even entertain.

For a while man was the king of the domain, using robots to make his every whim come true. Later as the home planet Earth becomes more and more polluted due to overuse of resources, mankind moves into habitats that are in orbit around the solar system. The robots can survive the harsh climates though. They stay on earth and evolve.

The last story shows a young human couple that tries coming back to the Earth, but is driven back to the orbiting habitat by Earth’s oppressive environment, and robots who are not comfortable with having human beings around in their society. They are now the superior race, who view humanity with the same disgust that apartheid filled westerners did East Indians, and Africans in the 1800s.

The book is tolerable, but not spectacular. The stories are inter-connected, but very loosely and the world changes so drastically in each story that you have trouble imagining the chain of events that could have created this new world. There are a lot of unanswered questions and gaps in the storyline. I would have been a lot more comfortable if Pohl hadn’t left them to the reader’s imagination.

But the book’s readable. I can give it that much credit. Some of the stories have turned out very nicely, like the one about Zeb, a farm robot who turns a unionist. I can see parallels with the communist movement here. :)

Compiling Selective code using compiler constants & directives

Sunday, June 29th, 2008

If you’re shipping a professional app with multiple users, you might have a need at times to ship customized levels of the apps according to the needs of the different user groups. Ex.,  you might need to ship a cut-down version of your application which may be sold for a lesser price, or given away as a demo. Kind of an ‘Express’, or ‘Lite’ version.

One way to do this is to copy the entire project to a different location, then remove those selected features and re-compile the app. This way however whenever you upgrade the application, or make modifications, you’ll have to do that at two places. Not a very effective technique then.

Another way is to set up regular constants and flags that you can use in your code to determine whether a certain feature should be activated. While this removes the upgrade problem in the technique above, it makes your application vulnerable. There’s a very high potential that a smart hacker will be able to debug your app, change a simple flag and get a full version instead of the trial. It’s been done too many times.

That’s why it’s better to use Compiler constants which remove the shortcomings of the above two techniques.

What is a compiler constant/directive?
In a program, most of the code you write targets the user. Be it your business logic, or interface validation, ultimately you’re talking to the user, but when you write compiler directives, or make use of compiler constants, you’re talking to the compiler.

Using compiler constants/symbols, you can set up variables that the compiler can access at compile time, and using compiler directives you can take action according to the state of these variables. You can ask the compiler to compile something, or not to compile something, or compile in a certain manner.

Here’s how you can do this

Set up a compiler constant in your code that you will use to flag whether you want to compile the lite version, or the full version. A good place to put this is the code file of the main window of your application, or your main class file. Here’s what the variable could look like in C#: -

#define trial;

Then in your code file you can use the #if, #else, #elif and #endif to separate the code that should be compiled. Remember, this is c# code, but the technique is universal and you can apply it in almost any language, including VB, C++, Delphi and Java.

#if trial
    MessageBox.Show("You need to buy the full version to access this feature.");

The code is self explanatory. If the compiler variable is set, you can show the user something entirely different. Maybe a limited feature, a nagscreen, or a message requesting them to purchase your software. This is totally secure, because you will be compiling a different trial version, and since your registered code is not going to be there, it will be very hard for someone to debug your application to remove the nag-screen.

When you need to compile the full version, just comment out the constant declaration like this: -

//#define trial;

Now when you compile your app, the compiler will not be able to find the trial variable and will thus compile the version which has full functionality.

So now you know how you can use this great approach to make separate versions of your software based on compiler constants. This can be a very powerful technique if put to good use. There’s only one limitation, you can’t have global compiler constants (at least not in C# and VB.Net). You’ll have to declare the variable in every file anew.

If you liked this article, or want to know something, drop me a line.

Redundant Else

Saturday, June 21st, 2008

Consider the following piece of code:

if (varga == Shodashvarga.Hora)
    if (rashi %2.00 == 0)
       return (Sign) (degrees <= 15 ? 4 : 5);
        return (Sign)(degrees <= 15 ? 5 : 4);

Do you think the else is redundant? Yeah, of course if you removed the else, the code would still work as expected, but removing it would make the code a LOT less readable. The else points it out, that the line below else is an alternative to the line above it. It’s CLEAR CODE. Removing it would make no difference to execution, but it would make a HUGE difference to readability.

That’s why I was irritated when resharper suggested that the else is redundant and that it can be removed.

Code-assistance is great for promoting disciplined programming, but it sure takes a disciplined programmer to avoid misusing it.

MySQL DB Import – Collation issue between Ver. 4 and 5

Saturday, June 21st, 2008

We’re migrating servers. It’s hard work shifting all the websites and the data from our older server to the new one. It takes up a lot of time, and about a million niggling issues crop up even though you think you’ve arranged for everything.

We host some blogs on the server. There are company blogs, product blogs, and some of our company people also have personal blogs on the server (like mine). All of them are on wordpress, and are hosted using Mysql DBs on a Windows server.

In the normal course transferring the blogs to a new server is easy: -

– Copy the entire folder contents of your blog to the new location.
– Create the db with the same name, and user on the new server.
– Use a utility like phpMyAdmin to export the blog data into SQL.
– Import the SQL into the new db.

Or use an automatic backup utility like backupwordpress to create a single-click backup. Then you can unzip the backup file created, copy the content into the folder, and use import the SQL file into your DB.

The last step, importing the SQL file is very important cause that’s where all your blog content is.

Our older server had MySQL 4, and the new one has Mysql five. When I tried importing the exported data from the older server into the new one, I got very weird behavior.

At first junk characters cropped up and the sql query failed altogether, when I tried a different approach (using backupwordpress’ sql), the query executed successfully, but all the data after the quotes ( ‘ ) would disappear.

The problem was with collation. By default (or magically), the collation in our db was set to latin_swedish_ci, and there’s no way to change the collation on a db once the data is put in. Due to the collation hassles there would be no way to just import-export the data into the new db (even when I set the collation in new db to swedish).

Most documented solutions advocated creating a new db with the correct collation, and copying the data into it table by table.

That’s what I finally did, but using phpMyAdmin, and a short-cut method.

The Method:
– I created an empty db on my new server, set up the user, and the correct collation.
– Then I used the phpMyAdmin interface to generate the SQL file of the db into a text-box (didn’t save as file) for each table.
– Then I copied the data, and pasted it into the import-sql box of my new db (again a text-box).

The query ran beautifully, and I was able to migrate all databases correctly. It raises a question though: Shouldn’t there be a better, easier way to manage or translate between collation?

If you know about it, please do tell us.

RSS – Brings Usenet to your reader

Saturday, June 21st, 2008

RSS is a wonder tech. It’s made many wonderful things possible. Bloggers syndicate their content, and sites like are able to consume that content and put all the bloggers together at one place. Internet websites, journals, etc., expose RSS feeds that you can use to keep abreast of the latest updates, some people make RSS feeds of even their Emails. There are many wonderful applications, but I recently found one that I think I am going to love.

I’ve always loved reading and being on newsgroups (Microsoft tech newsgroups, that is), but most newsreaders are bad, and the idea of downloading all those newsgroup posts daily put me off, so I subscribed only a to a few groups, and wasn’t able to follow them very regularly. Preferring instead to get all my learning dose and interaction through blogs using Google Reader.

I had to go to go to google groups to get something done today, and I found that google has exposed RSS feeds for Usenet group posts. Now I can put them in my google reader, and read usenet posts just like I read blog articles, or forum posts from ASP.Net.

That’s an excellent addition, and it’s brought me back into the Usenet world. If you’re not on usenet yet, use google groups and enjoy the Net.

Another recession around the corner?

Wednesday, June 11th, 2008

Here we stand, possibly on the verge of another great recession. Oil prices are at an all time high, inflation is up-up-up, bankers just made lending more expensive and realty is down-down-down. All good and clear signs that money supply is going to tighten and there might be another depression like the one we experienced a little less than a decade ago.

I read somewhere that the world sees a little recession every 12 years, and a big one every 25 years. I am almost 28 and still to see a big time recession like the one my parents experienced. Is one due now? I suspect the one now could be as big as the one in the early 2000s, but not quite like the 20s. We have come a long way since those days.

– The world economy is more connected. When there’s problem in one area, it’s compensated in another place.

– We’ve got a stabler system now. Economy is more mature, and there are newer cushions to take care of problems.

– Market forces too have more cushioning power due to widening of markets.

But seriously, since when did my gut feelings and analysis hold any water? In fact, let me give some counter arguments.

– The rise in the oil prices is unprecedented. It will put a huge dent in buyer sentiment. People might panic and put a hold on spendings.

– Rise in oil, steel, and basic raw materials affects everything. The inflation will be uncontrollable.

– Food production is not keeping up with demand. We could be sitting on a time-bomb here.

The picture I see is not rosy my friend. Not rosy at all.

Is it possible to stop crashes and panic situations like this? I believe there is. With careful and wiser use of our resources.

– Food production has to be rationalized. With more food going directly into the food chain. Turn vegetarian!

– Global population has to be lowered. Now haven’t we been hearing that since last 30 years?

– We need to reduce wasteful consumption. We really can’t afford to live like Americans on THIS planet.

– Stronger focus on de-centralized workplace so that we can work from our homes, or at least not have to travel 50 KMs to an urban center each day.

Bad TV Marketing Advice: Why it’s stupid to ask Panchhi Petha to organize Petha tours

Monday, June 9th, 2008

I don’t watch TV, but sometimes I channel surf. Yesterday I was channel surfing when something caught my eye and I stayed on for a couple of minutes. It was a show on brand promotion on one of the TV channels (don’t ask me which, and don’t ask me the name of the show either.) In the show some ‘marketing expert’ would go down to some city, pick up random business enterprises and dole out brand promotion advise to them. The city in question this time was Agra, the city I was born in, that’s why it caught my eye.

The questionable expert had picked on (and I mean picked ‘on’) poor Panchi Petha to shove brand promotion advise down their unsuspecting throats. Panchi Petha is the most popular Petha promotion brand of Agra, a synonym with good quality Petha. I’ve had a few boxes, so I can vouch their Petha is damn good. But the expert’s advice. It wasn’t any good. Here’s the advice: -

– Organize Petha tours for tourists, and show them how Pethas are made to generate interest in the Pethas –

Yep, that’s what you get when you put a questionable expert of questionable sense who has no idea of how Pethas or any other mithai is made in India.

When he says Petha tours, he’s probably re-visiting tours in Cadbury factory, coke, pepsi, or some other fully automated plant in his little head. If he had been inside a Petha manufacturing factory and had a good, careful look around he wouldn’t have mentioned ‘tour’, in fact he would have insisted that Panchhi Petha never, never show anyone their factory.

If tourists were taken to a Petha manufacturing facility, it wouldn’t generate interests in the Pethas, quite contrarily it would extinguish all interest that the tourists had in Pethas in the first place.

– Petha factories are not automated units in which every employee wears a mask, plastic glovers and blue overalls.
– They don’t have conveyor belts taking packed pethas from one deptt. to another, and a cute little bell that goes ding every time a packet is finished.

Here’s what you would find in a Petha factory.

– Stockpiles of green raw Pethas (big gourds), piled up on the floor. They don’t arrive in neatly labeled boxes.
– Huge woks, over-burnt and blackened from constant exposure to heat.
– Litres of chashni and about 10,000 flies trying to get into it.
– Aluminum trays placed on floor containing Pethas at all stages of preparation. No they’re not covered.
– Overweight halwais dorn in gamcha, baniyan, and a lungi, sweating and swearing over the huge woks.
– Empty tins of used vegetable oil set up in random places, and used to store cooked pethas.
– An old leaking tap that’s been leaking since such a long time that algae has grown around it. Discarded pants and shirts are hung over it. The halwais will wear them again when they go home.

Yes Mr. Brand expert, that’s your Petha tour. Take a tourist to one of these and you would have a hard time finding one ready to get video-taped happily plonking a Petha into her mouth.

So Mr. Panchi-Petha-Wale, no matter what Mr. Branding expert said, don’t think about organizing that Petha tour. He’s paid by the channel to look good and attract viewers, not to do real research and give you practical suggestions.

When Technology is no longer ‘Technology’

Sunday, June 8th, 2008

I’ve started reading a new book today. It’s called ‘The Future of Technology’, and is a compilation of articles on technology printed in the Economist over the last few years. There’s a strong thought expressed in the foreword. It says that when a new, exciting technology is launched, it undergoes an initial vibrant phase of quick growth and investment, then a big crash followed with a slower but more long-lasting phase of steady growth. Eventually it reaches a stage when it’s no longer considered a technology, and instead becomes a part of human life.

The author cited examples like mass-manufacturing technology, and railways.

It struck me as a pretty reasonable argument, and like Tom Standage said in the foreword, IT is on the crossroads now. It’s had its phase of extravagant investment, and then the crash, and now we have more stable growth. It is indeed part of lives now, and is slowly reaching a stage when it’s so common-place that it will no longer be a technology.

Very reasonable.

Another huge thought: IT has reached a stage where the technology does not matter anymore. What matters is how it is applied.

Yes, I believe in that. Although in a way that’s true right at the launch of any technology too, but even more so now that the technology is maturing and the market is now getting more-and-more trained in using IT tools properly.

I enjoyed the foreword, and since the book is not to be read as a whole, but in short articles, I suspect I will enjoy the book even more.