Escape Output
Another cornerstone of web application security is the practice of escaping outputescaping or encoding special characters so that their original meaning is preserved. For example, O’Reilly is represented as O\’Reilly when being sent to a MySQL database. The backslash before the apostrophe is there to preserve itthe apostrophe is part of the data and not meant to be interpreted by the database.
As with filtering input, when I refer to escaping output , I am really describing three different steps:
*
Identifying output
*
Escaping output
*
Distinguishing between escaped and unescaped data
To escape output, you must first identify output. In general, this is much easier than identifying input because it relies on an action that you take. For example, to identify output being sent to the client, you can search for strings such as the following in your code:
*
echo
*
print
*
printf
*
Welcome back, {$html[’username’]}.
“;
?>
Filtering Even Basic Values
HTML form elements have no types associated with them, and most pass strings (which may represent things such as dates, times, or numbers) to the server. Thus, if you have a numeric field, you cannot assume that it was entered as such. Even in environments where powerful client side code can try to make sure that the value entered is of a particular type, there is no guarantee that the values will not be sent to the server directly, as in the “Double Checking Expected Values” section.
An easy way to make sure that a value is of the expected type is to cast or convert it to that type and use it, as follows:
$number_of_nights = (int)$_POST[’num_nights’];
if ($number_of_nights == 0)
{
echo “ERROR: Invalid number of nights for the room!”;
exit;
}
If we have the user input a date in a localized format, such as “mm/dd/yy”‘ for users in the United States, we can then write some code to verify it using the PHP function called checkdate. This function takes a month, day, and year value (4-digit years), and indicates whether or not they form a valid date:
// split is mbcs-safe via mbstring (see chapter 5)
$mmddyy = split($_POST[’departure_date’], ‘/’);
if (count($mmddyy) != 3)
{
echo “ERROR: Invalid Date specified!”;
exit;
}
// handle years like 02 or 95
if ((int)$mmddyy[2] 50)
$mmddyy[2] = (int)$mmddyy[2] + 1900;
else if ((int)$mmddyy[2] >= 0)
$mmddyy[2] = (int)$mmddyy[2] + 2000;
// else it’s
C# preventing more than one application instance at a time
//check if previous instance of the application is already running
//get the name of our process
string proc = Process.GetCurrentProcess().ProcessName;//Get the list of all processes by that name
Process[] processes = Process.GetProcessesByName(proc);//if there is more than one process
if (processes.Length > 1)
{
MessageBox.Show(”A previous instance of the application is already running”);
return;
}
