1stwebdesigner

Posted by | Posted on 17:21

1stwebdesigner


A Beginner’s Guide to Secure Your Site from Web Trespassers

Posted: 22 Oct 2010 03:00 AM PDT

Information is everything. The web is full of free information for everyone to use but there are things that webmasters don’t want people to know, things that should be kept away from prying eyes. Be it an exclusive section on your website for premium users or content that thousands of users use,  it is best that you stuff-up your arsenal to avoid things go awry.

There is no such thing as an unhackable website, there are just those who are close to it or are offline. It is important to know how attacks are made in order to plan ahead.

Attacker’s Point of View

Image by: Benjamin Earwicker

First thing a hacker might want to know is information about your host and OS. From this they will learn of existing vulnerabilities, if there are, and hack their way in to your system. So choosing a web hosting that cares about security is very important, especially if you are on shared hosting where you are at the mercy of your host.

With today’s technology most websites have become more interactive where users can request and input data, personalize and manipulate the site. But interactivity provides loopholes in security. A good hacker will scan a target website thoroughly just to gain access to its server.

More below for in-depth discussion about attacks.

When a Hacker Attacks

Image by: eddmun

An experienced hacker does not attack blindly. When he attacks, he attacks with conviction (or curiosity). Usually they are armed with vital information that they can use to destabilize your site. Below are some of the most common forms of attacks:

  1. Defacement
  2. Defacement is common for government and celebrity websites as well as other innocent ones. Attacks like this can range from an act of retaliation to just simply for fun.

  3. Authorization Bypass
  4. A successful authorization bypass will make you shout “this is my code, not yours!”  Some hackers would actually want to have a piece of your code either to make a clone out of it or to destroy it.

  5. SQL Injection
  6. Then there is what we call SQL injection where the attacker inserts SQL queries in unsuspecting forms to extract information from the database that is not usually available even to your users: passwords, e-mails, and things you don’t want people to know. How will it impact you if a hacker drops your most important table and you do not have any back-up? Ouch!

  7. Cross-site Scripting(XSS)
  8. Another form of attack is Cross-site Scripting (XSS). Bad guy messes up with the good guys. What makes this kind of attack evil is it is easy to defend against but hard to detect. How will you defend if you are caught by surprise?

Image by: Ramasamy Chidambaram

I remember writing and submitting a simple script in an input field of a friend’s website which caused all users to see a pop-up whenever they load the homepage and be redirected to another website. Instant chaos. Of course this matter is easily fixed by simple input validation.

Image by: wikkedhill

Perhaps the best way to validate user input is not by specifying the should nots but by telling what is only allowed. To specify is to exclude. Less time and effort. Neat.

Security Guy Should Know

Image by: Julien Tromeur

There are many 3rd-party applications today, rate of birth is almost the same as Moore’s law. But is the guy in charge of security knowledgeable enough about these 3rd-party applications and the vulnerabilities they bring? If not, then trouble is looming, or you might opt to write your own modules.

Security guy should also know about Google Hack. Is Google still your friend? With advanced search query even the most seemingly impenetrable server text files can be harvested for everyone to see. By knowing what Robots.txt is, this form of attack can be stopped..for a while.

Run tests on your website using vulnerability scanners and website security audit. Try Acunetix and Beyond Security’s vulnerability scanners.

You can download Acunetix and BeyondSecurity’s trial scanners and find out flaws in and out of your website.

Although some good services do not come free, at least your website is secured.

If your CMS is WordPress refer to this comprehensive guide on Hardening WordPress.

Monitor Website Uptime

Image by: Chris Cockram

Is your website still working? Are people enjoying your services while you are away from your keyboard? You and security guy can’t be monitoring your website 24 hours a day just to maintain its availability (and stability), it’s just impossible. Let someone do the monitoring for you. SiteUptime’s service will alert you via SMS or e-mail if your website becomes unavailable. Some companies offering similar services are HostTracker, Internetseer, and WebSitePulse. Now every time you receive an SMS you will automatically think your website is down.

Hacked? It’s Not the End

If you feel like your security has been compromised, or really has been, do not act calmly. Connect to your FTP like your life is on the line and, if successful, change your password immediately to avoid further damage. Now you may breathe slowly. But in the event of failing to connect to your FTP you should immediately contact and notify the authorities for them to investigate the crime scene and your web host to regain your access as soon as possible.

I know it is hard to take your website offline, but in the case of your website being infected by a virus that attacks your visitors..take it offline, you must. Another way to take good care of them.

There are actually many forms of attacks, methodically these happen through FTP and through CGI vulnerabilities. It is wise to do research on your applications  for known vulnerabilities and if there are available patches. Always keep yourself, and your applications, updated!

Prevention is Better Than Cure

If you think you’ve done all what you can to secure your website but something still feels lacking, you might want to hire proven-and-tested security experts to try and break into your site, legally. They do not come cheap of course.

Below are experts in finding vulnerabilities, they offer almost the same services and boasts notable clients. Meet the good guys.

Rent-a-Hacker

Security Brigade

News and Updates

Updates are made in order to patch-up loopholes and add features. Not aware that something is wrong with your current applications? A good way to know if your website is secured is to learn of the current exploits that users and developers from around the web has found. There you, or your security guy, can formulate what to do next to patch it up. A comprehensive, and current, list of exploits can be found at Exploit-DB.com. Prevention is better than cure, as they say.

Also, be up to date of the current attacks that happen globally. A good news site about cyber attacks and other security news is CyberInsecure.com. Another gem that I found is SecurityFocus.com, it provides easy browsing of hundreds of vendors’ vulnerabilities. Sleek.

A person who is always up to date is never caught off guard. Good luck to all!

A Complete Beginner’s Guide to Zend Framework: Part 2

Posted: 22 Oct 2010 03:00 AM PDT

A Complete Beginner's Guide to Zend Framework: Part 2After reading the first part of our series, you've learned how to create a simple website based on Zend Framework. But it's necessary to keep the information for full web-application. In this part we will learn how to work with databases using ZF.

Zend_Db

Zend_Db_Adapter gives us an opportunity to work with different database management systems (DBMS).

Using PDO drivers:

  • BM DB2 and Informix Dynamic Server (IDS), using pdo_ibm extension
  • MySQL, using the pdo_mysql PHP extension
  • Microsoft SQL Server, using pdo_mssql
  • Oracle, using pdo_oci
  • PostgreSQL, using pdo_pgsql
  • SQLite, using the pdo_sqlite PHP extension

Using PHP extensions:

  • MySQL, using the mysqli extension
  • Oracle, using the oci8 PHP extension
  • IBM DB2, using ibm_db2
  • Firebird / Interbase, using php_interbase

We'll use the PDO driver to work with MySQL in this article.

Let’s Get Started

We need the way to store configuration file to the database connection. For it we'll create a application.ini file in our ./application/configs directory. Add to the file following lines:

	db.adapter          = "pdo_mysql" 	db.params.host      = "localhost" 	db.params.username  = "root" 	db.params.password  = "" 	db.params.dbname    = "your_db_name_here"

I think the content will not cause any difficulties for you. We will use Zend_Confg_Ini to parse the config of this file. You have to initialize connection to the database before dispatching process. Add the following code to your index.php file.

	// Load up our config file 	$config = new Zend_Config_Ini('./application/configs/application.ini', 'db');  	$db = Zend_Db::factory($config->db->adapter, 				   $config-db->config->toArray());  	// Return data as object 	$db->setFetchMode(Zend_Db::FETCH_OBJ);  	// The default adapter for table classes 	Zend_Db_Table::setDefaultAdapter($db);  	// Write our adapter to registry 	Zend_Registry::set('db', $db);

If you do not want to receive the result as an object, there are descriptions of other styles to obtain the result for you:

  • Zend_Db:: FETCH_ASSOC: returns the data in an associative array.
    The keys of the array are the column names. It's the mode of extraction is used by default in Zend_Db_Adapter classes.
  • Zend_Db:: FETCH_NUM: returns the data in an array. The array indexed by integers in accordance with the position of the field in the select query list.
  • Zend_Db:: FETCH_BOTH: returns the data in an array. The keys of the array are lines and integer values. The number of elements will produce twice more in the array than if FETCH_ASSOC or FETCH_NUM is used.
  • Zend_Db:: FETCH_COLUMN: returns the data in an array of values. The value is the value returned from one column of the result set in each array. By default, it's the first column, indexed by zero.
  • Zend_Db:: FETCH_OBJ: returns the data in an array of objects. By default, the built-in PHP class stdClass is used. Columns of the result of sample are available as public properties of this object.

You are probably interested why have we recorded the adapter to the registry? We did so to be able to get access to our created adapter in any controller or model. To extract our adapter from the registry back we can use Zend_Registry::get(); method

	Zend_Registry::get('db');

Well, let's try to execute some requests!

	$sql = 'SELECT * FROM users'; 	$result = $db->fetchAll($sql);

The $result variable will contain an array of objects. To extract a single column from the sample results you should do

	$sql = 'SELECT name, id FROM users'; 	$result = $db->fetchCol($sql);

Now $result contains only the name. In order to extract a single row from the result of sampling execute the following code

	$sql = 'SELECT * FROM users WHERE id = 2'; 	$result = $db->fetchRow($sql);

And now $result is the single object ($result->name). Extracting a single value

	$sql = 'SELECT COUNT(*) FROM users'; 	$result = $db->fetchOne($sql);

$result contains the number of users. That's all with SELECT queries. But we still have to add and modify our data in the database. Lets’s look at it.

Adding Records

There is a special method for inserting data to the database: Zend_Db’s insert method.

	$data = array('name'  => 'Nick', 				  'login' => 'nick',                   'email' => 'myemail@gmail.com');  	$db->insert('user', $data); 	$lastId = $db->lastInsertId();

We need to pass two parameters to insert method: table name, and an associative array with the data. lastInsertId method will return the value of auto-increment primary field in the table.

Updating Records

To able to update our db data we should call the update method and pass it three parameters. The first parameter is the name of the table, the second – an associative array with the data, the third parameter – a condition (optional); if you omit the third parameter, all records will be updated. The array of conditions can be passed as a WHERE condition.

	$data = array('name'  => 'Nick', 		          'login' => 'nick',                   'email' => 'myemail@gmail.com');  	$db->update('user', $data, 'id = 1');

Deleting Records

Now you should know what each parameter is used for. The first argument is the name of the table, the second is the condition. Simply, right? Also there may be several conditions which is passed as an array. If you omit the second argument, all records of the table will be deleted.

	$db->delete('user', 'id = 1');

Example Bits of Code

Example 1:

	// Extract Zend_Db_Select 	$select = $db->select();	  	// 1st - table name, 2nd - array of selecting columns 	$select->from('news', array('YEAR(date) AS yearNews', 		'MONTH(date) AS monthNews', 		'DAy(date) AS dayNews'));

Example 2:

	// Extract Zend_Db_Select 	$select = $db->select();	  	// Descending sorting 	$select->from('news')->order('date DESC'); 	$result = $db->fetchAll($select);

Example 3:

	// Extract Zend_Db_Select 	$select = $db->select();	  	// Descending sorting by date and ascending by title field 	$select->from('news') 		->order(array('date DESC', 'title'));  	$result = $db->fetchAll($select);

Example 4:

	// Extract Zend_Db_Select 	$select = $db->select();	  	// Descending sorting by date and ascending by title field 	$select->from(array('n' => 'news'), // table name and its alias 				array('newsTitle' => 'title', // The second parameter 						'newsDescription' => 'description', // column alias => column name 					'date' => 'date')) 			->join(array('a' => 'author'), // The first param for join method | alias => table name 					array('n.author = a.id'), // The 2nd param - array of condition for join operator 					array('name' => 'authorName')) // Associative array of columns 			->order('date DESC'); // Sorting descending by date column  	$result = $db->fetchAll($select);

Zend_Db_Select

Zend_Db_Select – is the assistant of making SELECT queries. Using this class methods we can build our complicated queries expressions part-by-part.

Queries Building

For example, we have to choose the record of news from a table with this query

	SELECT * FROM news WHERE id = 12;

Using Zend_Db_Select it would look like so

	// Extract Zend_Db_Select 	$select = $db->select();  	$select->from('news')->where('id = 12'); 	$result = $db->fetchAll($select);

Now, let’s choose all the news records, but breaking the date's field into three columns – year, month, day

SELECT *, YEAR(date) AS yearNews, 	MONTH(date) AS monthNews, 	DAY(date) AS dayNews FROM news;

SQL has several types of joining operation. Below are the list of methods for supporting different joining types in Zend_Db_Select.

  • INNER JOIN, methods join (table, join, [columns]) and joinInner (table, join, [columns]).
  • LEFT JOIN, the method joinLeft (table, condition, [columns]).
  • RIGHT JOIN, the method joinRight (table, condition, [columns]).
  • FULL JOIN, the method joinFull (table, condition, [columns]).
  • CROSS JOIN, the method joinCross (table, [columns]).
  • NATURAL JOIN, the method joinNatural (table, [columns]).

There are also some special methods of Zend_Db_Select class.

  • orWhere() – the same as where(), but with logical OR.
  • group() – one column's name can be sent to this method by one line or the lines' array of columns' names./li>
  • limit() – passes the desired number of rows to choose by the first parameter, by the second – number of the optional rows which can be omitted.

The Result

Another one Zend Framework lesson is completed. Digest the received knowledge, and I hope we will try to continue our experiment in the next part. Bye!

P.S. I look forward to receiving your feedback and questions in the comments below.

Comments (0)

Post a Comment