Environment specific configuration in zend


In software development life cycle, we generally need different type of environments for different purpose like – “development”, “testing”, “production” etc.

And all these environments has some environment specific configuration. like in development server “display error” will be on and payment mode will be “testmode” But in production server “display error” will be off and payment mode will be “livemode” In production server error logging will be on but in testing server it may not be on. Database connection will be different for each environment. etc etc…

Problem:

Its been a big headache to server management team to modify configuration files each time code update to any server.
Here we have created multiple configuration files for each server and automatically loaded environment wise configuration file using “zend-framework”.

Solution:

Here we will consider 3 environment- “Production”, “QA” and “Development” in order to explain the process.
So we will create 4 ini files:
common_config.ini: to keep common configuration (which don’t change with environments)
app_prod.ini: “Production” server specific configuration
app_QA.ini: “QA” server specific configuration
app_dev.ini: “Development” server specific configuration

common_config.ini:

[Production]
phpSettings.error_log = [path to file] "/application.log"

includePaths.application = APP_PATH
includePaths.library = APP_LIB

bootstrap.path = [path to file] "/Bootstrap.php"
bootstrap.class = "Project_Bootstrap"

autoloadernamespaces.0 = "Project"

resources.frontController.moduleControllerDirectoryName = "controllers"
resources.frontController.moduleDirectory = [path to file] "/modules"

resources.frontController.defaultControllerName = "index"
resources.frontController.defaultAction = "index"
resources.frontController.defaultModule = "account"
[QA : Production]
[Development : Production]

Look at last 2 lines- it is saying QA and Development server both will extend configuration from Production.

app_prod.ini:

[Production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
phpSettings.log_errors = 1

;payment related credentials
payment.mode = "liveMode"
;db configuration
resources.db.adapter = "Pdo_Mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "user1"
resources.db.params.password = "pass1"
resources.db.params.dbname = "db_prod"

app_QA.ini:

[QA]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
phpSettings.log_errors = 1

;payment related credentials
payment.mode = "testMode"
;db configuration
resources.db.adapter = "Pdo_Mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "user2"
resources.db.params.password = "pass2"
resources.db.params.dbname = "db_qa"

app_dev.ini:

Similar to QA. you now know what will be in this configuration file. 🙂

So we made ready all configuration files. Now need to load proper configuration for environments.
index.php file will contain something like this:

 

defined('COMMON_CONFIG_INI_PATH') || define('COMMON_CONFIG_INI_PATH',
        [path to file] . '/Config/common_config.ini');

// set APP_INI_PATH according to environment
switch (APP_ENV) {
    case 'Production' :
        defined('APP_INI_PATH') || define('APP_INI_PATH',
            [path to file] . '/Config/app_prod.ini');
        break;
    case 'QA' :
        defined('APP_INI_PATH') || define('APP_INI_PATH',
            [path to file] . '/Config/app_QA.ini');
        break;
    case 'Development' :
        defined('APP_INI_PATH') || define('APP_INI_PATH',
            [path to file] . '/Config/app_dev.ini');
}

defined('APP_LOG_PATH') || define('APP_LOG_PATH',
        realpath(dirname(__FILE__) . '/../logs'));

//Bootstrap the application
require_once('Zend/Application.php');
//load zend_app with config file and run
$application = new Zend_Application(APP_ENV,
        array(
            'config' => array(
                        COMMON_CONFIG_INI_PATH,
                        APP_INI_PATH
                       )
             )
    );
$application->bootstrap()->run();

So here we we have set 2 constant for configuration files according to environment: COMMON_CONFIG_INI_PATH and APP_INI_PATH
and loaded these 2 configuration while bootstrapping.

You are done. Nothing more. Simple, isn’t it? 🙂

Advertisements

Common Session Attacks (Session Fixation and Session Hijacking)


We developers use session protected functionality to restrict unwanted access, to provide security.  Do we know there are 2 very popular session attacks?

In the first type of attack, attacker can hijack any user’s session and use that same session to grab illegal privilege. This is called “session hijacking”.

In the second type of attack, attacker tricks to use her own specified session to victim which in turn disclose victims valuable details. In this way attacker fixes victim’s session, hence called “session fixation”.

In the both ways the main target is to use the same session which victim is using.

Procedure of Attack:

Except the initial step both type are same.

Session Fixation: This process starts before victim logs in. First atacker logs into the system and receive a valid session identifier (say sessionid = abcd). now attacker sets the victim’s session even bofore victim logs in.

Fixation

Following are 2 basic way to trick user-

http://anywebsite.com/<script>document.cookie=”sessionid=abcd”;</script>
http://anywebsite.com/<meta http-equiv=Set-Cookie content=”sessionid=abcd”>

Now if victim clicks on this type of link their session set to “abcd”. Now when victim logs in, same session id gets associated to his session.

Session Hijacking: In this process attacker try to grab a session which victim is using.

Following are few basic way to attack-

using cross site scripting –

<SCRIPT>alert(document.cookie);</SCRIPT>

Man-in-the-middle attack
Man-in-the-browser attack

Now the attacker impersonate as victim as she is using same session as victims session, and do whatever she wants.

Prevention:

Session Fixation:

-> Since Session Fixation starts before login, we can create a new session whenever an user logs in, hence preventing using of an existing session.
-> Use session_regenerate_id();

Session Hijacking:

Session hijacking cannot be directly prevented, however we can put steps in to make it very difficult and harder to use. Remember how difficult we can make it, attacker will leave and look for a softer target

-> Use a strong session hash identifier: session.hash_function in php.ini. If PHP < 5.3, set it to “session.hash_function = 1” for SHA1.
If PHP >= 5.3, set it to session.

hash_function = sha256

or

session.hash_function = sha512

-> “session.hash_bits_per_character = 5” in php.ini. When the attacker tries to guess the session identifier the ID will be shorter, but uses more characters.
-> Change the default session name from PHPSESSID to something else.
-> Save $_SERVER[‘HTTP_USER_AGENT’] in session and check in every request for user agent.

Defend attackers 🙂

References:
http://shiflett.org/articles/session-hijacking
https://www.owasp.org/index.php/Session_fixation
http://stackoverflow.com/questions/5081025/php-session-fixation-hijacking

Grocery CRUD : CodeIgniter


Grocery Crud is a CodeIgniter CRUD. It is fully tested in codeigniter 2.0 and in 1.7.x. You don’t need so much line of codes, models , views, libraries to make a CRUD works. Just few lines need to write and a stable CRUD is ready.

Grocery CRUD is a codeigniter CRUD library that makes a php developer’s life easier.
Simple and many Features!

Even for complex CRUDs you can use it by adding callbacks. You can choose the CRUD template that you want to use by changing only the theme. You are able to build the grid and the forms easily and automatically by using the power of jquery.

The different themes currently available  are: List View

  • Datatables
  • FlexGrid
  • Twitter-Bootstrap

The good part is that you don’t even have to change the CSS to make it more user friendly. Grocery CRUD is ready for the production mode with all the required security and views.
Grocery CRUD is an automatic CRUD generator and it can cover almost all your needs for a CRUD system (simple or complex one) as it has many features and still keep going.

Features

  • Change themes easily.
  • Grid listing with paging, sorting, searching by field and search for all with ajax (with all themes)
  • Automatic creation of inputs by field type
    (Field types that auto-generate different inputs are: integer, string, text, date, datetime, set, enum, true_false(0 or 1), hidden, password and readonly)
  • Database relation 1-1 , 1-n and n-n , automatically with just one line of code
  • Validation form with client side validation and server side validation
  • Add your own validation rules
  • Have Flexibility to choose columns and fields that you want to add to your table
  • CALLBACKS almost everywhere to do your own customization
  • Can add your own model or by extending the basic model
  • Supports all modern browsers, such as: Mozilla Firefox, Google Chrome,Opera, Safari, Internet Explorer 9 or later and also supports for all the modern OS systems such as Windows, Linux, MACOS
  • MOBILE compatible, works fine with the default browsers of Android , Windows and iPhone.

Installation

The installation is really easy. Need to download grocery crud zip from here http://www.grocerycrud.com/downloads

After this, You need to just copy all the files to your project and you are ready to use grocery CRUD. By the end of the installation, your file structure should look similar to this.
driectory display

After this, you are ready to use.

Enjoy Coding! 🙂

Reference: http://www.grocerycrud.com/

HOW  XSS attack handled by different PHP frameworks?


As we know PHP is Open Source, so we can play over it. It also has list of Frameworks to follow for web development.But, while doing development we have to take care about XSS attacks. Now, Question arrise 🙂

What  is XSS?

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in form of a browser side script, to a different end user. These attacks can occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page.

Basically, there are two types of XSS attacks:
1.) Stored: due to malicious code is saved on the server, and then sent to the end users, without proper encoding
2.) Reflected: due to malicious code is usually sent to the server in GET or POST parameters in http request, and the server returns that code in response, without proper encoding
It can be protect with :
a.) Filter input, escape output
b.) character encoding

How PHP FramWorks Handle XSS?
  • Yii– output escaping with integrated HTMLPurifier
  • Kohana2 – input filtering / global XSS filter
  • Kohana3 – input filtering, they recommend output escaping with HTMLPurifier, but it’s not included
  • CakePHP – offered a utility called Sanitize, but it is deprecated as of CakePHP 2.4 and will be removed in CakePHP 3.0
  • CodeIgniter – input filtering / global XSS filter
  • Zend Framework – custom output escaping
  • HTMLPurifier is a great solution when you need to display clean HTML that came from untrusted source, but for escaping every piece of data, which won’t be displayed as HTML, is overkill.
  • Global XSS filtering is a very bad idea, beacuse of the reason we mentioned above, you don’t know in which context the data will be used.
  • Sanitize : add() – Sanitize the data in the controller before saving
    beforeSave() – Sanitize the data in the model callback before saving
    afterFind() – Sanitize the data in the model callback after finding
  • OWASP has good security encoding library, but unfortunately, PHP version is not complete yet. They have a good reference for this matter. View
Example:
<body><?php echo htmlencode($untrusted_var); ?></data>
<input value=”<?php echo htmlencode($untrusted_var); ?>” />
While we can in most cases just use php’s htmlentities function.
So, it’s better to write custom wrapper functions, so we can change code only in one place if, for example, we want to add additional filtering or switch to another library.
function htmlencode($str) {
    $str = HTMLPurifier_Encoder::cleanUTF8($str);
    $str = htmlspecialchars($str, ENT_QUOTES, ‘UTF-8’);
    return $str;
}
This function will encode all html characters and prevent breaking the context.
If you need to write user data which contains html, HTMLPurifier will do the job.
I hope this will help you to understand XSS and to use it in your web development eailsy. 🙂
Enjoy Coding!