Wednesday, February 17, 2010

Shell Scripting Continued...

Hi Folks

Along with my previous commitment about posting further more on Shell Scripting and on request from few about same, here I am again with few more details on it.

In this blog, I would try to answer basic Why, How and Where about Shell Scripting.

I received ample of comments with basic yet very valid question that

Why Should I need to write Shell Scripts ?

Here are some usage I have tried to quote :

1. Operating Systems likes Linux and other Unix-like needs automated tasks. Shell scripts are extremely useful for achieving this.
2. Shell scripts are also employed extensively in the default installations of Unix-like operating systems.
3. In daily life, programmers might need to execute series of commands most often. Executing those several commands manually at a command line interface, Shell scripts allow it to be executed automatically. And that too without having to wait for a user to trigger each stage of the sequence.

For example, in a directory with three C source code files, rather than manually running the four commands required to build the final program from them, one could instead create a C shell script, and keeping in the directory with them, which would compile them automatically.

These types of programs are also called as Batch jobs.

4. A shell script can be used to provide a sequencing and decision-making linkage around existing programs, and for moderately-sized scripts the absence of a compilation step is an advantage.
5. Shell scripts can also be useful at a need where scripts requires executed :
  1. Interactively
  2. Once, at a future date and time
  3. Repeatedly on a fixed schedule
  4. Using an HTML form

Next, I would like to shed light on How to create shell Script ?

What all I would like to mention here to answer this question is that all that is necessary to create this script is to open a plain text editor (but not a word processor), such as vim, emacs, gedit, dtpad et cetera are all valid, any text editor will do. And type the series of commands to execute them. Thats it !! Its that simple !! For adding commands to be executed, you can refer my previous post on same topic. It would help you understand the syntaxes, variables, arithmatics to be used etc. in script.

Consider a very basic example of printing Date of the System :

Filename : myDate.sh

#!/bin/bash
set `date`
echo $1 $2 $3 $6

Alternatively, the above code could be copied from this page and pasted to a blank page opened by the text editor page using the standard keyboard or mouse copy and paste functions.

After saving this plain text file, with a file name such as date (or anything else desired), the script is complete and almost ready to run. Scripts are typically run by typing a dot, a forward slash and the file name (with no spaces in between) and then pressing the ENTER key. You would come to know further ways to execute the script from command prompt down below.

Thus, for example, if the above script were saved with the name morning, an attempt could be made to execute it by issuing the following command:

./myDate

Script will print the output as : sat Aug 5 2006

However, the script probably will not run, in which case an error message will appear on the screen such as bash: ./myDate: Permission denied.

This is because the permissions for the file first have to be set to executable. (By default, the permissions for new files are set to read and write only.) The problem can easily be solved by using the chmod command with its 755 option (which will allow the file creator to read, write and execute the file) while in the same directory as that in which the file is located as follows:

chmod 755 morning

Now the script is totally ready to run..


Finally Where would I execute the Script ? is the question remained..

Command Prompt !! This is what all I can answer to this. Ha ha. Yes, serious I am. Consider you have named your script as foo. (Well, I dont know why foo. :) Its just like that !! LOL ). So once you are done writing your script, you would simply go to the command prompt and type any of following command to execute your script..
  • $ bash foo
  • $ sh foo
  • $ ./foo


Finally, I would like to share one Shell Scripting example with Menu Program ::

fnMainMenu()
{
clear
echo "======= Menu ==========="
echo "Menu :"
echo " (1) Addition"
echo " (2) Quit this Menu"
echo "Enter your option : "
read response
case $response in
1) echo "Enter First Number : "
read num1
echo "Enter Second Number : "
read num2
sum=`expr $num1 + $num2`
echo "Addition : $sum "
;;
2) exit
;;
*) echo "I dont know what you are trying?"
sleep 2
;;
esac
}
#===== Start =====
#!/bin/sh
fnMainMenu


Try this program !!

Hope I have been successful in explaining the more basics about the Shell Script and was able to answer most of your doubts on this, so feel free to share your views on this.

Monday, February 15, 2010

SQL Injection

Hello Folks, Long time no see !! I know I was also missing writing since couple of months. To fulfill my hunger of writing and your hunger of reading, here I am ready with another topic to shed some light on...

Our Todays topic is SQL Injection..

Another common vulnerability which is result of slipshod input validations is SQL Injection. Generally cross-site scripting vulnerabilities are actually directed to your site's visitors whereas SQL Injection is something which directly attacks on your site itself – to be specific its Database.

Target of SQL Injection activity is to insert arbitrary data, mostly DB Queries, which are eventually executed by the Database using your script only. The subtle query may attempt any no. of actions starting from retrieving the records till removing significantly all records from database including altering or modifying the same.

[In this blog, I have used PHP Scripting Lang. extensively, but note, it is possible with any Scripting language and PHP is used as I love it.. ;P ]

To demonstrate it in more detail, look at the below example :

Consider a simple query where I want to retrieve the user name and password of user named 'Sandip'.

$strSelectQuery ="Select username, password from tbl_Users where user_name='".$userName."'"

For this Query, in my script I am taking user name as in a variable:

$userName = "sandip"

So that it would make my call as :
mysql_query("Select username, password from tbl_Users where user_name='".$userName."'");

Simple ain't it ? But here's the glitch..

What would happen if instead of simple 'sandip' input some enters:

$userName = "sandip’; DELETE FROM users;"

By appending an entirely new query to $userName, the call to the database turns into disaster: the injected DELETE query removes all records from users.

Still Confused how ? Ok here, if notice the single quote and semi-colon given in user input, those two entities will complete the first query successfully causing next query for Delete User stacked in queue and getting it executed will remove all of those users off the table.

Hoohh !!! Scary huh ??

But don't worry, PHP is here to rescue, Magic Quotes is something provided by PHP. This is PHP's automatic input escaping mechanism. magic_quotes_gpc, provides some basic protection. If "magic quotes" enabled, it adds a backslash in front of single-quotes, double-quotes and other characters that could be used to break out of a value identifier. If not enabled, you can still use addslashes feature given by PHP in combination to protect at moderate level.

E.g.
if (!get_magic_quotes_gpc()) {
$userName= addslashes($userName);
}

$strSelectQuery ="Select username, password from tbl_Users where user_name='".$userName."'"

Wondering how escaping would help ! Ok, carefully note, in first illustration, it was single quote which caused our first query completed making second one stacked and executed. How if we do not let our first query itself completed ?? Yeah, you got it !! escaping single quotes from input string would add slashes in it and would in turn hold the query to be completed forcefully by user input.

There are many of the database extensions available for PHP include dedicated, customized

escape mechanisms. E.g. the MySQL extension for PHP provides the function mysql_real_escape_string() to escape input characters that are special to MySQL and if you are not much interested in using addslashes you can surely tweak the code as :

if (get_magic_quotes_gpc()) {
$userName = stripslashes($userName);
}

$userName = mysql_real_escape_string($userName);

$strSelectQuery ="Select username, password from tbl_Users where user_name='".$userName."'"

Note, here before giving a call to the function, checking magic code state is important in else case input would be escaped twice.

Ouch !! Unfortunately, escaping the single quote does not always guarantee you security of your code from SQL Injection. There are certain queries that still allows SQL Injection despite of you escaping the input. Consider following example, you would know what I mean :

$user_id = "0; DELETE FROM tbl_Users";

$user_id = mysql_real_escape_string($user_id); // 0; DELETE FROM

If you note here, we are expecting a numeric value as an input to our query, and as you know it’s not necessary to enclose the value inside single quotes. Thus, even if we escape the input, there is nothing to escape and hence still causing the second injected query of delete execute successfully causing our Database severe damage.

But don't worry, we still have solution to this problem as well. How about Casting feature of PHP. As we know, we gotto have numeric value as an input. Why don't we cast it ?? Feeling good to know this...

So, if an integer is required, cast the incoming datum to an int; if a complex number is required, cast to a float. As simple as that Lets see one illustration for this as well :

$user_id = "0; DELETE FROM tbl_Users";
$user _id = (int) $user_id; // 123
$strSelectQuery ="Select username, password from tbl_Users where user_name='".$userName."'"

A cast forces PHP to perform a type conversion. If the input is not entirely numeric, only the leading numeric portion is used. If the input doesn’t start with a numeric value or if the input is only alphabetic and punctuation characters, the result of the cast is 0. On the other hand, if the cast is successful, the input is a valid numeric value and no further escaping is needed.

Numeric casting is not only very effective, it’s also efficient, since a cast is a very fast, function-free operation that also obviates the need to call an escape routine.

Aahh !! Relax, Now we are much safe here !!!

Hope you all have read the article and found helpful to take care of those things in your development !! Feel Free to share your feedback...