Introduction
Websites today are more complex than ever, containing a lot of dynamic content making the experience for the user more enjoyable. Dynamic content is achieved through the use of web applications which can deliver different output to a user depending on their settings and needs. Dynamic websites suffer from a threat that static websites don't, called "Cross Site Scripting" (or XSS dubbed by other security professionals). Currently small informational tidbits about Cross Site Scripting holes exist but none really explain them to an average person or administrator. This FAQ was written to provide a better understanding of this emerging threat, and to give guidance on detection and prevention.
"What is Cross Site Scripting?"
Cross site scripting (also known as XSS) occurs when a web application gathers malicious data from a user. The data is usually gathered in the form of a hyperlink which contains malicious content within it. The user will most likely click on this link from another website, instant message, or simply just reading a web board or email message. Usually the attacker will encode the malicious portion of the link to the site in HEX (or other encoding methods) so the request is less suspicious looking to the user when clicked on. After the data is collected by the web application, it creates an output page for the user containing the malicious data that was originally sent to it, but in a manner to make it appear as valid content from the website. Many popular guestbook and forum programs allow users to submit posts with html and javascript embedded in them. If for example I was logged in as "john" and read a message by "joe" that contained malicious javascript in it, then it may be possible for "joe" to hijack my session just by reading his bulletin board post. Further details on how attacks like this are accomplished via "cookie theft" are explained in detail below.
"What does XSS and CSS mean?"
Often people refer to Cross Site Scripting as CSS. There has been a lot of confusion with Cascading Style Sheets (CSS) and cross site scripting. Some security people refer to Cross Site Scripting as XSS. If you hear someone say "I found a XSS hole", they are talking about Cross Site Scripting for certain.
"What are the threats of Cross Site Scripting?"
Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool a user (Read below for further details) in order to gather data from them. Everything from account hijacking, changing of user settings, cookie theft/poisoning, or false advertising is possible. New malicious uses are being found every day for XSS attacks. The post below by Brett Moore brings up a good point with regard to "Denial Of Service", and potential "auto-attacking" of hosts if a user simply reads a post on a message board.
"What can I do to protect myself as a vendor?"
This is a simple answer. Never trust user input and always filter metacharacters. This will eliminate the majority of XSS attacks. Converting < and > to < and > is also suggested when it comes to script output. Remember XSS holes can be damaging and costly to your business if abused. Often attackers will disclose these holes to the public, which can erode customer and public confidence in the security and privacy of your organization's site. Filtering < and > alone will not solve all cross site scripting attacks and it is suggested you also attempt to filter out ( and ) by translating them to ( and ), and also # and & by translating them to # (#) and & (&).
"What can I do to protect myself as a user?"
The easiest way to protect yourself as a user is to only follow links from the main website you wish to view. If you visit one website and it links to CNN for example, instead of clicking on it visit CNN's main site and use its search engine to find the content. This will probably eliminate ninety percent of the problem. Sometimes XSS can be executed automatically when you open an email, email attachment, read a guestbook, or bulletin board post. If you plan on opening an email, or reading a post on a public board from a person you don't know BE CAREFUL. One of the best ways to protect yourself is to turn off Javascript in your browser settings. In IE turn your security settings to high. This can prevent cookie theft, and in general is a safer thing to do.
"How common are XSS holes?"
Cross site scripting holes are gaining popularity among hackers as easy holes to find in large websites. Websites from FBI.gov, CNN.com, Time.com, Ebay, Yahoo, Apple computer, Microsoft, Zdnet, Wired, and Newsbytes have all had one form or another of XSS bugs.
Every month roughly 10-25 XSS holes are found in commercial products and advisories are published explaining the threat.
"Does encryption protect me?"
Websites that use SSL (https) are in no way more protected than websites that are not encrypted. The web applications work the same way as before, except the attack is taking place in an encrypted connection. People often think that because they see the lock on their browser it means everything is secure. This just isn't the case.
"Can XSS holes allow command execution?"
XSS holes can allow Javascript insertion, which may allow for limited execution. If an attacker were to exploit a browser flaw (browser hole) it could then be possible to execute commands on the client's side. If command execution were possible it would only be possible on the client side. In simple terms XSS holes can be used to help exploit other holes that may exist in your browser.
"What if I don't feel like fixing a CSS/XSS Hole?"
By not fixing an XSS hole this could allow possible user account compromise in portions of your site as they get added or updated. Cross Site Scripting has been found in various large sites recently and have been widely publicized. Left unrepaired, someone may discover it and publish a warning about your company. This may damage your company's reputation, depicting it as being lax on security matters. This of course also sends the message to your clients that you aren't dealing with every problem that arises, which turns into a trust issue. If your client doesn't trust you why would they wish to do business with you?
CROSS SITE SCRIPTING VALIDATIONS:
1) Examples of regular expressions that may help block cross site scripting:
- A possible regular expression, which will deny the basic cross site scripting variants might be: ^([^<]
|\<[^a-zA-Z])*[<]?$
2) A generic regular expression, which will deny all of the aforementioned characters might be: ^
([^\<\>\"\'\%\;\)\(\&\+]*)$
ColdFusion,Dotnet,JavaScript,Html,SqlServer and Everything
About Programming Tips and Tricks
Thursday, February 26, 2009
Error Codes
Here are more standard web error numbers. You can see the headers and output at Apache Status Codes and ErrorDocuments
* 100 Continue
* 101 Switching Protocols
* 102 Processing
* 200 OK
* 201 Created
* 202 Accepted
* 203 Non-Authoritative Information
* 204 No Content
* 205 Reset Content
* 206 Partial Content
* 207 Multi-Status
* 300 Multiple Choices
* 301 Moved Permanently
* 302 Found
* 303 See Other
* 304 Not Modified
* 305 Use Proxy
* 307 Temporary Redirect
* 400 Bad Request
* 401 Authorization Required
* 402 Payment Required
* 403 Forbidden
* 404 Not Found
* 405 Method Not Allowed
* 406 Not Acceptable
* 407 Proxy Authentication Required
* 408 Request Time-out
* 409 Conflict
* 410 Gone
* 411 Length Required
* 412 Precondition Failed
* 413 Request Entity Too Large
* 414 Request-URI Too Large
* 415 Unsupported Media Type
* 416 Requested Range Not Satisfiable
* 417 Expectation Failed
* 422 Unprocessable Entity
* 423 Locked
* 424 Failed Dependency
* 425 No code
* 426 Upgrade Required
* 500 Internal Server Error
* 501 Method Not Implemented
* 502 Bad Gateway
* 503 Service Temporarily Unavailable
* 504 Gateway Time-out
* 505 HTTP Version Not Supported
* 506 Variant Also Negotiates
* 507 Insufficient Storage
* 510 Not Extended
* 100 Continue
* 101 Switching Protocols
* 102 Processing
* 200 OK
* 201 Created
* 202 Accepted
* 203 Non-Authoritative Information
* 204 No Content
* 205 Reset Content
* 206 Partial Content
* 207 Multi-Status
* 300 Multiple Choices
* 301 Moved Permanently
* 302 Found
* 303 See Other
* 304 Not Modified
* 305 Use Proxy
* 307 Temporary Redirect
* 400 Bad Request
* 401 Authorization Required
* 402 Payment Required
* 403 Forbidden
* 404 Not Found
* 405 Method Not Allowed
* 406 Not Acceptable
* 407 Proxy Authentication Required
* 408 Request Time-out
* 409 Conflict
* 410 Gone
* 411 Length Required
* 412 Precondition Failed
* 413 Request Entity Too Large
* 414 Request-URI Too Large
* 415 Unsupported Media Type
* 416 Requested Range Not Satisfiable
* 417 Expectation Failed
* 422 Unprocessable Entity
* 423 Locked
* 424 Failed Dependency
* 425 No code
* 426 Upgrade Required
* 500 Internal Server Error
* 501 Method Not Implemented
* 502 Bad Gateway
* 503 Service Temporarily Unavailable
* 504 Gateway Time-out
* 505 HTTP Version Not Supported
* 506 Variant Also Negotiates
* 507 Insufficient Storage
* 510 Not Extended
cross site scripting
cross site scripting:
A Quick Look at Cross Site Scripting
We may not be able to completely bulletproof our websites, but we can at least try to anticipate possible attacks and secure against them. Here is one you might not have heard of: cross site scripting. With just a bit of JavaScript, a malicious attacker can use it to cause all sorts of problems. To find out more about what it is, and how to prevent your website from becoming a victim, keep reading.
Introduction
The question keeps spinning in our minds, just like a ball bouncing deeply inside the brain: is our website really secure? Surely, that’s a very tough topic to answer. But one thing is true in all cases: there are not any websites “completely” safe from attacks. Given the uncontrolled and anonymous nature of the Internet, the concept of a bulletproof website is merely a pipe dream.
More specifically, Web servers are inherently public machines, being accessible by many people around the world, and clearly exposed to several well-known attack techniques. The value of the information stored on servers varies widely, depending on what kind of sites they are hosting, but it’s always appealing to potential attackers. However, there is a lot that we can do about securing our website.
We are well aware of many attack methods which might end up exposing, modifying, or deleting sensitive data, so our site is well assured against them. Also, we have updated our software accordingly, stopped unnecessary services on the server, closed unused TCP ports, encrypted data, and the like. What else could be vulnerable? Many times, it’s not properly considered or ignored: assumptions made by developers.
Designers and programmers need to make many assumptions. Hopefully, they will document their assumptions and usually be right. Sometimes thought, developers will make poor assumptions. These might include that input data will be valid, will not include unusual characters or will be a fixed length. That brings us almost immediately to the well-known “SQL Injections,” widely documented in several articles on the Web, in conjunction with Cross Site Scripting attacks. Here is where this article comes in.
In the rest of the article, I'll cover what Cross Site Scripting is, how it works and how it can be avoided, increasing our site’s security level and, hopefully, bringing an overall improvement to our security strategy.
A Quick Look at Cross Site Scripting - What is Cross Site Scripting?
To understand what Cross Site Scripting is, let’s see a usual situation, common to many sites. Let’s say we are taking some information passed in on a querystring (the string after the (?) character within a URL), with the purpose of displaying the content of a variable, for example, the visitor’s name:
http://www.yourdomain.com/welcomedir/welcomepage.php?name=John
As we can see in this simple querystring, we are passing the visitor’s name as a parameter in the URL, and then displaying it on our “welcomepage.php” page with the following PHP code:
<?php
echo ‘Welcome to our site ’ . stripslashes($_GET[‘name’]);
?>
The result of this snippet is shown below:
Welcome to our site John
This is pretty simple and straightforward. We’re displaying the content of the “name” variable, by using the $_GET superglobal PHP array, as we have done probably hundreds of times. Everything seems to be fine. Now, what’s wrong with this code? Nothing really. But let’s modify the querystring by replacing our visitor’s name passed in the URL:
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=John
with something like this:
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=
<script language=javascript>alert
(‘Hey, you are going to be hijacked!’);</script>
Do you remember the PHP code included in our “welcome.php” page? Yes, you’re correct. When we modify the querystring, the following code is executed:
<?php
echo ‘Welcome to our site ‘ .
<script language=javascript> alert(‘Hey, you are going
to be hijacked!’);</script>
?>
The output of this code is an alert JavaScript box telling you “Hey, you are going be hijacked!” after the “Welcome to our site” phrase.
Very ugly stuff, right? That’s a simple example of the Cross Site Scripting vulnerability. This means that any pasted JavaScript code into the URL will be executed happily with no complaints at all.
Keep reading. There‘s more yet to be revealed!
A Quick Look at Cross Site Scripting - Going deeper into JavaScript
Following the same concept above described, we might build a new URL for achieving more dangerous and annoying effects. It’s just a matter of including a little bit of JavaScript.
For instance:
http://www.yourdomain.com/welcomedir/welcomepage.php?
name=<script language=javascript>window.location=
”http://www.evilsite.com”;</script>
It’s getting more complex now. As we can appreciate, a JavaScript redirection will take place to “www.evilsite.com”, just by including the above URL in the browser location bar. At first glance, it’s not as bad as it seems. After all, we haven’t seen anything that could significantly harm our website. But, is it really true? Let’s present a new example, which might quickly change your mind.
We’ll demonstrate how easy is to manipulate URLs and inject JavaScript into them, for malicious purposes.
For example:
http://www.yourdomain.com/welcomedir/welcomepage.php?
name=<script language=javascript>setInterval
("window.open('http://www.yourdomain.com/','innerName')",100);
</script>
Now, let’s explain in detail what’s going on here. We have inserted JavaScript code to making a request for the http://www.yourdomain.com index page every 100 milliseconds. The setInterval() method is taking care of the task, but other JavaScript methods, such as setTimeout() with a recursive implementation would do the trick too. The code could either heavily overload the Web server where our site is located or generate a Denial of Service condition by denying access to other visitors requesting the same page (or other pages), and inflict noticeable damage to the server performance. On the other hand, it would be harmful to our website’s reputation, just because other users cannot get access to it. Not very good, huh?
Please note that a similar attack effect might be achieved by manipulating sockets with PHP or any other programming language, but that’s another huge subject, out of the scope of this article. Anyway, keeping your sharp eyes open to unusual levels of traffic is a must. So, don’t ever forget to take a look at your site’s logs files and use software for monitoring traffic and real time statistics.
Unfortunately, there are a huge number of ways to attack websites using Cross Site Scripting, embedding JavaScript code into the URL. From relatively innocent and harmless scripts, to risky and harmful code, we have to try to prevent or avoid them.
If this is not enough, we’ll see another common Cross Site Scripting technique: hiding JavaScript code within links.
A Quick Look at Cross Site Scripting - The hidden link
Adding JavaScript code into querystrings is a quite easy stuff to get done, so the same concept is applied to regular links. This is easily deductible, since all of the previous examples presented have manipulated absolute links directly from the location bar. Thus, relative and absolute links within documents or email messages can be tampered too.
An example is useful to properly understand how this technique works:
<a href=”http://www.yourdomain.com/welcomedir/
welcomepage.php?name=<script language=javascript>window.location=’
http://www.evilsite.com’;</script>”>healthy food</a>
If we take a deeper look at the code above listed, we can see clearly what’s going on. Within the regular link, the JavaScript code is inserted to redirect users to a completely different site. The expression seems to be an apparently innocent link, but it’s in fact hiding something else, the JavaScript embedded in the link.
We might send out this link to someone else, so our unworried recipient would click the link to find out a little more about healthy food, and instead being redirected to a different site location, getting something he or she would never expect to see.
Our site’s reputation could be seriously wounded, as we can fairly imagine, if someone is taking care of sending around our URL with the JavaScript code embedded in the link, to numerous recipients. That would result in the nasty redirecting effect previously described. And recipients wouldn’t be happy about it at all!
Having presented the most commonly used Cross Site Scripting techniques, we need to tackle a proper solution to avoid their ugly effects and prevent ourselves from becoming victims of them.
Let’s see how the problem can be solved.
A Quick Look at Cross Site Scripting - Preventing Cross Site Scripting
First off, we need to follow simple and straight rules, applicable to common scenarios, where user input is always involved.
Always, all the time, and constantly (pick your term), check to ensure what’s coming from POST and GET requests. However obvious, you should never pass by these steps.
If a specific and particular type of data is expected, check to ensure that it’s a really valid type and that its of the expected length. Whatever programming language you’re using will give you the possibility and the power to do that easily.
Whenever possible, use client-side validation for adding extra functionality to user input checking. Please note that JavaScript validation cannot be used on its own for checking data validity, but it may help to discourage some evil-minded visitors from entering malicious data while providing useful assistance to other well-intended users.
Remove conflicting characters from user input. Search for < and > characters and make sure they're quickly removed. Single and double quotes must be escaped properly too. Many professional websites fail when dealing with character escaping. I hope you won’t.
We might go on endlessly, with numerous tips about validating user data, but you can get a lot more from just checking some other useful tutorials and articles. For the sake of this article, we’ll show an example to prevent Cross Site Scripting using PHP.
A Quick Look at Cross Site Scripting - Coding for our safety
Let’s define a simple function to prevent the querysting from being tampered with external code. The function “validateQueryString()” is the following:
<?php
function validateQueryString ( $queryString , $min=1,
$max=32 ) {
if ( !preg_match ( "/^([a-zA-Z0-9]{".$min.",".$max."}=[a-zA-Z0-9]{".$min.",".$max."}&?)
+$/", $queryString ) ) {
return false;
}
return true;
}
?>
Once we have defined this function, we call it this way:
<?php
$queryString = $_SERVER[‘QUERY_STRING’];
if ( !validateQueryString ( $queryString ) ) {
header( ‘Location:errorpage.php’ );
}
else {
echo ‘Welcome to our site!’;
}
?>
Let’s break down the code to see it in detail.
The function performs pattern matching to the querystring passed as a parameter, checking to see if it matches the standard format of a querystring, including GET variable names that only contain the numbers 0-9 and valid letters either in lowercase or uppercase. Any other characters will be considered as invalid. Also, we have specified as a default value that variables can be from 1 to 32 characters long. If matches are not found, the function returns false. Otherwise, it will return true.
Next, we have performed validation on the querystring by calling the function. If it returns false -- that is, the querystring contains invalid characters -- the user will be taken to an error page, or whatever you like to do. If the function returns true, we just display a welcome message.
Of course, most of the time, we really know what variables to expect, so our validation function can be significantly simplified.
Given the previous URL,
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=John
where the “name” variable is expected, we might write the new “validateAlphanum()” function:
<?php
function validateAlphanum( $value , $min = 1 , $max =
32 ) {
if ( !preg_match( "/^[a-zA-Z0-9]{".$min.",".$max."}
$/", $value ) ) {
return false;
}
return true;
}
?>
and finally validate the value like this:
<?php
$name = $_GET[‘name’];
if ( !validateAlphanum ( $name ) ) {
header( ‘Location:errorpage.php’ );
}
else {
echo ‘Welcome to our site!’;
}
?>
The concept is the same as explained above. The only noticeable difference is that we’re taking in the “name” variable as the parameter for the “validateAlphanum()” function and checking if it contains only the allowed characters 0-9, a-z and A-Z. Anything else will be considered an invalid input.
If you’re a strong advocate of object oriented programming, as I am, we might easily include this function as a new method for an object that performs user data validation. Something similar to this:
<?php
$name = $_GET[‘name’];
// get variable value
$dv = &new dataValidator();
// instantiate new data
validator object
if ( !$dv->validateAlphanum( $name ) ) {
// execute validation method
header( ‘Location:errorpage.php’ );
}
else {
echo ‘Welcome to our site!’;
}
?>
Pretty simple, isn’t it?
In order to avoid Cross Site Scripting, several approaches can be taken, whether procedural or object-oriented programming is your personal taste.
In both cases, we’ve developed specific functions to validate querystrings and avoid tampered or unexpected user input data, demonstrating that Cross Site Scripting can be prevented easily with some help coming from our favorite server-side language.
Conclusion
As usually, dealing with user input data is a very sensitive issue, and Cross Site Scripting falls under this category. It is a serious problem that can be avoided with some simple validation techniques, as we have seen through this article.
Building up robust applications that won’t make poor assumptions about visitor’s input is definitely the correct way to prevent Cross Site Scripting attacks and other harmful techniques. Client environments must always be considered as a pretty unsafe and unknown territory. So, for the sake of your website’s sanity and yours, keep your eyes open.
A Quick Look at Cross Site Scripting
We may not be able to completely bulletproof our websites, but we can at least try to anticipate possible attacks and secure against them. Here is one you might not have heard of: cross site scripting. With just a bit of JavaScript, a malicious attacker can use it to cause all sorts of problems. To find out more about what it is, and how to prevent your website from becoming a victim, keep reading.
Introduction
The question keeps spinning in our minds, just like a ball bouncing deeply inside the brain: is our website really secure? Surely, that’s a very tough topic to answer. But one thing is true in all cases: there are not any websites “completely” safe from attacks. Given the uncontrolled and anonymous nature of the Internet, the concept of a bulletproof website is merely a pipe dream.
More specifically, Web servers are inherently public machines, being accessible by many people around the world, and clearly exposed to several well-known attack techniques. The value of the information stored on servers varies widely, depending on what kind of sites they are hosting, but it’s always appealing to potential attackers. However, there is a lot that we can do about securing our website.
We are well aware of many attack methods which might end up exposing, modifying, or deleting sensitive data, so our site is well assured against them. Also, we have updated our software accordingly, stopped unnecessary services on the server, closed unused TCP ports, encrypted data, and the like. What else could be vulnerable? Many times, it’s not properly considered or ignored: assumptions made by developers.
Designers and programmers need to make many assumptions. Hopefully, they will document their assumptions and usually be right. Sometimes thought, developers will make poor assumptions. These might include that input data will be valid, will not include unusual characters or will be a fixed length. That brings us almost immediately to the well-known “SQL Injections,” widely documented in several articles on the Web, in conjunction with Cross Site Scripting attacks. Here is where this article comes in.
In the rest of the article, I'll cover what Cross Site Scripting is, how it works and how it can be avoided, increasing our site’s security level and, hopefully, bringing an overall improvement to our security strategy.
A Quick Look at Cross Site Scripting - What is Cross Site Scripting?
To understand what Cross Site Scripting is, let’s see a usual situation, common to many sites. Let’s say we are taking some information passed in on a querystring (the string after the (?) character within a URL), with the purpose of displaying the content of a variable, for example, the visitor’s name:
http://www.yourdomain.com/welcomedir/welcomepage.php?name=John
As we can see in this simple querystring, we are passing the visitor’s name as a parameter in the URL, and then displaying it on our “welcomepage.php” page with the following PHP code:
<?php
echo ‘Welcome to our site ’ . stripslashes($_GET[‘name’]);
?>
The result of this snippet is shown below:
Welcome to our site John
This is pretty simple and straightforward. We’re displaying the content of the “name” variable, by using the $_GET superglobal PHP array, as we have done probably hundreds of times. Everything seems to be fine. Now, what’s wrong with this code? Nothing really. But let’s modify the querystring by replacing our visitor’s name passed in the URL:
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=John
with something like this:
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=
<script language=javascript>alert
(‘Hey, you are going to be hijacked!’);</script>
Do you remember the PHP code included in our “welcome.php” page? Yes, you’re correct. When we modify the querystring, the following code is executed:
<?php
echo ‘Welcome to our site ‘ .
<script language=javascript> alert(‘Hey, you are going
to be hijacked!’);</script>
?>
The output of this code is an alert JavaScript box telling you “Hey, you are going be hijacked!” after the “Welcome to our site” phrase.
Very ugly stuff, right? That’s a simple example of the Cross Site Scripting vulnerability. This means that any pasted JavaScript code into the URL will be executed happily with no complaints at all.
Keep reading. There‘s more yet to be revealed!
A Quick Look at Cross Site Scripting - Going deeper into JavaScript
Following the same concept above described, we might build a new URL for achieving more dangerous and annoying effects. It’s just a matter of including a little bit of JavaScript.
For instance:
http://www.yourdomain.com/welcomedir/welcomepage.php?
name=<script language=javascript>window.location=
”http://www.evilsite.com”;</script>
It’s getting more complex now. As we can appreciate, a JavaScript redirection will take place to “www.evilsite.com”, just by including the above URL in the browser location bar. At first glance, it’s not as bad as it seems. After all, we haven’t seen anything that could significantly harm our website. But, is it really true? Let’s present a new example, which might quickly change your mind.
We’ll demonstrate how easy is to manipulate URLs and inject JavaScript into them, for malicious purposes.
For example:
http://www.yourdomain.com/welcomedir/welcomepage.php?
name=<script language=javascript>setInterval
("window.open('http://www.yourdomain.com/','innerName')",100);
</script>
Now, let’s explain in detail what’s going on here. We have inserted JavaScript code to making a request for the http://www.yourdomain.com index page every 100 milliseconds. The setInterval() method is taking care of the task, but other JavaScript methods, such as setTimeout() with a recursive implementation would do the trick too. The code could either heavily overload the Web server where our site is located or generate a Denial of Service condition by denying access to other visitors requesting the same page (or other pages), and inflict noticeable damage to the server performance. On the other hand, it would be harmful to our website’s reputation, just because other users cannot get access to it. Not very good, huh?
Please note that a similar attack effect might be achieved by manipulating sockets with PHP or any other programming language, but that’s another huge subject, out of the scope of this article. Anyway, keeping your sharp eyes open to unusual levels of traffic is a must. So, don’t ever forget to take a look at your site’s logs files and use software for monitoring traffic and real time statistics.
Unfortunately, there are a huge number of ways to attack websites using Cross Site Scripting, embedding JavaScript code into the URL. From relatively innocent and harmless scripts, to risky and harmful code, we have to try to prevent or avoid them.
If this is not enough, we’ll see another common Cross Site Scripting technique: hiding JavaScript code within links.
A Quick Look at Cross Site Scripting - The hidden link
Adding JavaScript code into querystrings is a quite easy stuff to get done, so the same concept is applied to regular links. This is easily deductible, since all of the previous examples presented have manipulated absolute links directly from the location bar. Thus, relative and absolute links within documents or email messages can be tampered too.
An example is useful to properly understand how this technique works:
<a href=”http://www.yourdomain.com/welcomedir/
welcomepage.php?name=<script language=javascript>window.location=’
http://www.evilsite.com’;</script>”>healthy food</a>
If we take a deeper look at the code above listed, we can see clearly what’s going on. Within the regular link, the JavaScript code is inserted to redirect users to a completely different site. The expression seems to be an apparently innocent link, but it’s in fact hiding something else, the JavaScript embedded in the link.
We might send out this link to someone else, so our unworried recipient would click the link to find out a little more about healthy food, and instead being redirected to a different site location, getting something he or she would never expect to see.
Our site’s reputation could be seriously wounded, as we can fairly imagine, if someone is taking care of sending around our URL with the JavaScript code embedded in the link, to numerous recipients. That would result in the nasty redirecting effect previously described. And recipients wouldn’t be happy about it at all!
Having presented the most commonly used Cross Site Scripting techniques, we need to tackle a proper solution to avoid their ugly effects and prevent ourselves from becoming victims of them.
Let’s see how the problem can be solved.
A Quick Look at Cross Site Scripting - Preventing Cross Site Scripting
First off, we need to follow simple and straight rules, applicable to common scenarios, where user input is always involved.
Always, all the time, and constantly (pick your term), check to ensure what’s coming from POST and GET requests. However obvious, you should never pass by these steps.
If a specific and particular type of data is expected, check to ensure that it’s a really valid type and that its of the expected length. Whatever programming language you’re using will give you the possibility and the power to do that easily.
Whenever possible, use client-side validation for adding extra functionality to user input checking. Please note that JavaScript validation cannot be used on its own for checking data validity, but it may help to discourage some evil-minded visitors from entering malicious data while providing useful assistance to other well-intended users.
Remove conflicting characters from user input. Search for < and > characters and make sure they're quickly removed. Single and double quotes must be escaped properly too. Many professional websites fail when dealing with character escaping. I hope you won’t.
We might go on endlessly, with numerous tips about validating user data, but you can get a lot more from just checking some other useful tutorials and articles. For the sake of this article, we’ll show an example to prevent Cross Site Scripting using PHP.
A Quick Look at Cross Site Scripting - Coding for our safety
Let’s define a simple function to prevent the querysting from being tampered with external code. The function “validateQueryString()” is the following:
<?php
function validateQueryString ( $queryString , $min=1,
$max=32 ) {
if ( !preg_match ( "/^([a-zA-Z0-9]{".$min.",".$max."}=[a-zA-Z0-9]{".$min.",".$max."}&?)
+$/", $queryString ) ) {
return false;
}
return true;
}
?>
Once we have defined this function, we call it this way:
<?php
$queryString = $_SERVER[‘QUERY_STRING’];
if ( !validateQueryString ( $queryString ) ) {
header( ‘Location:errorpage.php’ );
}
else {
echo ‘Welcome to our site!’;
}
?>
Let’s break down the code to see it in detail.
The function performs pattern matching to the querystring passed as a parameter, checking to see if it matches the standard format of a querystring, including GET variable names that only contain the numbers 0-9 and valid letters either in lowercase or uppercase. Any other characters will be considered as invalid. Also, we have specified as a default value that variables can be from 1 to 32 characters long. If matches are not found, the function returns false. Otherwise, it will return true.
Next, we have performed validation on the querystring by calling the function. If it returns false -- that is, the querystring contains invalid characters -- the user will be taken to an error page, or whatever you like to do. If the function returns true, we just display a welcome message.
Of course, most of the time, we really know what variables to expect, so our validation function can be significantly simplified.
Given the previous URL,
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=John
where the “name” variable is expected, we might write the new “validateAlphanum()” function:
<?php
function validateAlphanum( $value , $min = 1 , $max =
32 ) {
if ( !preg_match( "/^[a-zA-Z0-9]{".$min.",".$max."}
$/", $value ) ) {
return false;
}
return true;
}
?>
and finally validate the value like this:
<?php
$name = $_GET[‘name’];
if ( !validateAlphanum ( $name ) ) {
header( ‘Location:errorpage.php’ );
}
else {
echo ‘Welcome to our site!’;
}
?>
The concept is the same as explained above. The only noticeable difference is that we’re taking in the “name” variable as the parameter for the “validateAlphanum()” function and checking if it contains only the allowed characters 0-9, a-z and A-Z. Anything else will be considered an invalid input.
If you’re a strong advocate of object oriented programming, as I am, we might easily include this function as a new method for an object that performs user data validation. Something similar to this:
<?php
$name = $_GET[‘name’];
// get variable value
$dv = &new dataValidator();
// instantiate new data
validator object
if ( !$dv->validateAlphanum( $name ) ) {
// execute validation method
header( ‘Location:errorpage.php’ );
}
else {
echo ‘Welcome to our site!’;
}
?>
Pretty simple, isn’t it?
In order to avoid Cross Site Scripting, several approaches can be taken, whether procedural or object-oriented programming is your personal taste.
In both cases, we’ve developed specific functions to validate querystrings and avoid tampered or unexpected user input data, demonstrating that Cross Site Scripting can be prevented easily with some help coming from our favorite server-side language.
Conclusion
As usually, dealing with user input data is a very sensitive issue, and Cross Site Scripting falls under this category. It is a serious problem that can be avoided with some simple validation techniques, as we have seen through this article.
Building up robust applications that won’t make poor assumptions about visitor’s input is definitely the correct way to prevent Cross Site Scripting attacks and other harmful techniques. Client environments must always be considered as a pretty unsafe and unknown territory. So, for the sake of your website’s sanity and yours, keep your eyes open.
Sunday, February 15, 2009
Passing a Table to a Stored Procedure
Introduction
SQL Server 2005 and previous versions do not support passing a table variable to a stored procedure
The CODE
This article is based on SQL Server 2008 CTP 3. Some of the information may change by the time the product is finally released.
Before we create a Function or Stored Procedure that accepts a TABLE variable, we need to define a User Defined TABLE Type. SQL Server 2008 introduced a new User defined TABLE type. A TABLE type represents the structure of a table that can be passed to a stored procedure or function.
So the first step is to create a User Defined TABLE type. The following TSQL code creates a User defined TABLE type named "ItemInfo".
1 CREATE TYPE ItemInfo AS TABLE
2 (
3 ItemNumber VARCHAR(50),
4 Qty INT
5 )
You can use the system view SYS.TYPES to see the type that you have just created. The following query returns all the types defined in the system.
1 SELECT * FROM SYS.TYPES
2
3 /*
4 If you just need to find information about the TABLE types, you could find it from
5 the following TSQL query.
6 */
7
8 SELECT * FROM SYS.TYPES WHERE is_table_type = 1
9
10 /*
11 There is another view, which is handy to find information about TABLE types.
12 */
13
14 SELECT * FROM SYS.TABLE_TYPES
We have created a TABLE type that we need. Now let us see how it works. Let us create a variable of type "ItemInfo" and try to insert a few records to it. Then lets query the table variable to see if the information is correctly inserted. [code]
1 /*
2 Let us declare a variable of type ItemInfo which is a TABLE Type
3 */
4 DECLARE @items AS ItemInfo
5
6 /*
7 Insert values to the variable
8 */
9
10 INSERT INTO @Items (ItemNumber, Qty)
11 SELECT '11000', 100 UNION ALL
12 SELECT '22000', 200 UNION ALL
13 SELECT '33000', 300
14
15 /*
16 Lets check if the values are correctly inserted or not
17 */
18 SELECT * FROM @Items
19
20 /*
21 OUTPUT:
22
23 ItemNumber Qty
24 -------------------------------------------------- -----------
25 11000 100
26 22000 200
27 33000 300
28 */
Now let us create a stored procedure that accepts a TABLE variable. Let us create a very simple stored procedure which accepts a TABLE variable and SELECTs contents of the table.
1 CREATE PROCEDURE TableParamDemo
2 (
3 @Items ItemInfo
4 )
5
6 AS
7
8 SELECT *
9 FROM @Items
Well, this would generate the following error:
1 /*
2 Msg 352, Level 15, State 1, Procedure TableParamDemo, Line 1
3 The table-valued parameter "@Items" must be declared with the READONLY option.
4 */
A table variable that is passed to a stored procedure or function should be marked as READONLY. The "callee" cannot modify the table being passed into it. Here is the correct code.
1 CREATE PROCEDURE TableParamDemo
2 (
3 @Items ItemInfo READONLY
4 )
5
6 AS
7
8 SELECT *
9 FROM @Items
Now let us execute the stored procedure we just created. Run the following code.
1 /*
2 declare the variable
3 */
4 DECLARE @items AS ItemInfo
5
6 /*
7 Insert values to the variable
8 */
9
10 INSERT INTO @Items (ItemNumber, Qty)
11 SELECT '11000', 100 UNION ALL
12 SELECT '22000', 200 UNION ALL
13 SELECT '33000', 300
14
15 /*
16 Execute the procedure
17 */
18 EXECUTE TableParamDemo @Items
19
20 /*
21 OUTPUT:
22
23 ItemNumber Qty
24 -------------------------------------------------- -----------
25 11000 100
26 22000 200
27 33000 300
28
29 */
You cannot modify the TABLE parameter passed into the stored procedure. If you try to do so, you will get an error as shown in the following example.
1 CREATE PROCEDURE TableParamDemo
2 (
3 @Items ItemInfo READONLY
4 )
5
6 AS
7
8 SELECT *
9 FROM @Items
10
11 INSERT INTO @Items (ItemNumber, Qty)
12 SELECT '1001', 20
13
14 /*
15 OUTPUT:
16
17 Msg 10700, Level 16, State 1, Procedure TableParamDemo, Line 11
18 The table-valued parameter "@Items" is READONLY and cannot be modified.
19 */
Conclusions
The support for TABLE variables is very interesting. While working with User Defined TABLE Type, please note that you cannot use it as a column of a table. Please also note that, once created, you cannot alter the structure of the TABLE.
SQL Server 2005 and previous versions do not support passing a table variable to a stored procedure
The CODE
This article is based on SQL Server 2008 CTP 3. Some of the information may change by the time the product is finally released.
Before we create a Function or Stored Procedure that accepts a TABLE variable, we need to define a User Defined TABLE Type. SQL Server 2008 introduced a new User defined TABLE type. A TABLE type represents the structure of a table that can be passed to a stored procedure or function.
So the first step is to create a User Defined TABLE type. The following TSQL code creates a User defined TABLE type named "ItemInfo".
1 CREATE TYPE ItemInfo AS TABLE
2 (
3 ItemNumber VARCHAR(50),
4 Qty INT
5 )
You can use the system view SYS.TYPES to see the type that you have just created. The following query returns all the types defined in the system.
1 SELECT * FROM SYS.TYPES
2
3 /*
4 If you just need to find information about the TABLE types, you could find it from
5 the following TSQL query.
6 */
7
8 SELECT * FROM SYS.TYPES WHERE is_table_type = 1
9
10 /*
11 There is another view, which is handy to find information about TABLE types.
12 */
13
14 SELECT * FROM SYS.TABLE_TYPES
We have created a TABLE type that we need. Now let us see how it works. Let us create a variable of type "ItemInfo" and try to insert a few records to it. Then lets query the table variable to see if the information is correctly inserted. [code]
1 /*
2 Let us declare a variable of type ItemInfo which is a TABLE Type
3 */
4 DECLARE @items AS ItemInfo
5
6 /*
7 Insert values to the variable
8 */
9
10 INSERT INTO @Items (ItemNumber, Qty)
11 SELECT '11000', 100 UNION ALL
12 SELECT '22000', 200 UNION ALL
13 SELECT '33000', 300
14
15 /*
16 Lets check if the values are correctly inserted or not
17 */
18 SELECT * FROM @Items
19
20 /*
21 OUTPUT:
22
23 ItemNumber Qty
24 -------------------------------------------------- -----------
25 11000 100
26 22000 200
27 33000 300
28 */
Now let us create a stored procedure that accepts a TABLE variable. Let us create a very simple stored procedure which accepts a TABLE variable and SELECTs contents of the table.
1 CREATE PROCEDURE TableParamDemo
2 (
3 @Items ItemInfo
4 )
5
6 AS
7
8 SELECT *
9 FROM @Items
Well, this would generate the following error:
1 /*
2 Msg 352, Level 15, State 1, Procedure TableParamDemo, Line 1
3 The table-valued parameter "@Items" must be declared with the READONLY option.
4 */
A table variable that is passed to a stored procedure or function should be marked as READONLY. The "callee" cannot modify the table being passed into it. Here is the correct code.
1 CREATE PROCEDURE TableParamDemo
2 (
3 @Items ItemInfo READONLY
4 )
5
6 AS
7
8 SELECT *
9 FROM @Items
Now let us execute the stored procedure we just created. Run the following code.
1 /*
2 declare the variable
3 */
4 DECLARE @items AS ItemInfo
5
6 /*
7 Insert values to the variable
8 */
9
10 INSERT INTO @Items (ItemNumber, Qty)
11 SELECT '11000', 100 UNION ALL
12 SELECT '22000', 200 UNION ALL
13 SELECT '33000', 300
14
15 /*
16 Execute the procedure
17 */
18 EXECUTE TableParamDemo @Items
19
20 /*
21 OUTPUT:
22
23 ItemNumber Qty
24 -------------------------------------------------- -----------
25 11000 100
26 22000 200
27 33000 300
28
29 */
You cannot modify the TABLE parameter passed into the stored procedure. If you try to do so, you will get an error as shown in the following example.
1 CREATE PROCEDURE TableParamDemo
2 (
3 @Items ItemInfo READONLY
4 )
5
6 AS
7
8 SELECT *
9 FROM @Items
10
11 INSERT INTO @Items (ItemNumber, Qty)
12 SELECT '1001', 20
13
14 /*
15 OUTPUT:
16
17 Msg 10700, Level 16, State 1, Procedure TableParamDemo, Line 11
18 The table-valued parameter "@Items" is READONLY and cannot be modified.
19 */
Conclusions
The support for TABLE variables is very interesting. While working with User Defined TABLE Type, please note that you cannot use it as a column of a table. Please also note that, once created, you cannot alter the structure of the TABLE.
coldfusion 8 pdf download
>>Download coldfusion 8 pdf
coldfusion 8 new features
Adobe Flex integration
ColdFusion 8 now includes Adobe LiveCycle® Data Services ES (formerly Flex™ Data Services) and other data exchange improvements to simplify the data-enabling of rich Internet applications (RIAs) you build with ColdFusion and Flex.
Image manipulation
ColdFusion 8 adds more than 50 new tags and functions for creating and manipulating images, from simple to sophisticated. For example, the new CFIMAGE tag provides shortcuts to the most common image actions, including reading, writing, resizing, rotating, and converting images.
Atom and RSS feeds
ColdFusion 8 introduces the new CFFEED tag, which can read and create RSS and Atom feeds in commonly used formats, so you can quickly and easily create complex content syndication applications.
Improved file manipulation functions
ColdFusion 8 adds several new file manipulation functions to the ColdFusion Markup Language (CFML), most notably the ability to read and write large files in defined segments, rather than in a single operation.
JavaScript operators in CFML
ColdFusion 8 supports common JavaScript operators such as ++, ==, ||, <, and > so they can be used in CFML expressions.
CFC improvements
ColdFusion 8 adds several highly requested improvements to ColdFusion components (CFCs), including the ability to create interface definitions, use J2EE session replication in a cluster, have access to the CFCs in session data across all the machines in a cluster, and use the new onMissing Method function
Reporting enhancements
ColdFusion 8 introduces a completely new version of the ColdFusion Report Builder. Use it to create high-quality, structured reports with more output choices and a more consistent look and feel throughout your applications. You can also create and apply cascading style sheet (CSS) definitions to reports, export your reports in HTML or XML format, and create report styles for all of your reports.
Database interaction improvements
ColdFusion 8 provides a new DBINFO tag to programmatically access information about a data source, allows stored procedures and queries using CFQUERYPARAM to be cached, and much more. Plus, there is expanded database driver support with new options for SQL Server 2005, Oracle 10g, Sybase ASE15, MySQL 4 and 5, PostgreSQL 8, and others.
Array and structure creation improvements
ColdFusion 8 allows you to create arrays and structures implicitly in assignment statements without using the ArrayNew or Structnew functions. The result is cleaner code with less typing
Download coldfusion 8 pdf
Wednesday, February 11, 2009
sitemap
Site Map
Homepage
Page generated by XML-Sitemaps.com - A Google sitemaps and html sitemaps generator
|
Copyright © 2006, 2007
Subscribe to:
Posts (Atom)