Zero Down the security issues in PHP by using PHP Frameworks

As per Open Web Application Security Project (OWASP) there are top 10 security issues. Unfortunately PHP openness allows hackers to exploit  it.

Use PHP Frameworks to avoid hackers

1) Injection Injecting code as part of the actual command or query in order to break or hostile the system. This can be SQL Injection, OS Injection or LDAP injection. This occupies the top list of security flaws.

Using  php prepared statements  would avoid the sql injection. Unfortunately php don’t force the programmer to use the prepared statements. Zend Framework’s  Zend_DB class is internally uses prepared statements.

$db = Zend_Db::factory('Pdo_Mysql', array(
    'host'     => 'localhost',
    'username' => 'user',
    'password' => 'xxxxxx',
    'dbname'   => 'lead'
));

$stmt = $db->query('SELECT * FROM contacts WHERE name = ? AND status = ?',
    array('Alex', 'prospect')
);

$rows = $stmt->fetchAll();

The parameters to prepared statements don’t need to be quoted; the driver automatically handles this.
If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible.
2) Broken Authentication and Session Management – Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities.

Zend_Auth class provides an API for authentication and includes solid authentication adapters for common use case scenarios listed below,

  • Zend_Auth_Adapter_DbTable
  • Zend_Auth_Adapter_Digest
  • Zend_Auth_Adapter_Http
  • Zend_Auth_Adapter_Ldap
  • Zend_Auth_Adapter_OpenId

 

$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

$authAdapter
    ->setTableName('users')
    ->setIdentityColumn('username')
    ->setCredentialColumn('password')
    ->setIdentity('my_username')
    ->setCredential('my_password');

$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
    $storage->write($adapter->getResultRowObject(
        null,
        'password'
    ));
}

3) Cross-Site Scripting (XSS) –  XSS occurs when an application takes the data as it is and sends to the server without performing any validation. The hacker can induce malicious code within the data input. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

$this->escape() from Zend_View class classically solves the XSS issue.

StripTags, StringTrim and HtmlEntities also some basic PHP functions to avois XSS.

4)  Insecure Direct Object References – A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Zend_file and zend_db are used to handle the files and safely. unset function of PHP is very safe to use. If the object is not needed it must be cleared out using the unset() function.

5) Security Misconfiguration – Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date.

Zend could not give us the direct solution to the security misconfiguration flaw. But adhering to the below standard would avoid falling on wrong hands.

a)       Keep your production environment up to date which includes OS, Frameworks, DB and all kind of 3rd party libraries or code.

b)       Disable unwanted settings. Setting up the nominal code execution time (max_execution_time), limit the file upload size, always keep the display_errors setting off in production environment.

c)       Change your default user names and passwords. Always use strong and unique passwords for every account

d)       By including single line “Options -Indexes” on your .htaccess  avoid listing your directory when some one browse your website.

e)     Delete unwanted  files, such as configuration or install ation files.

f)        Always use proper error handling methods to avoid showing up the default errors.

6)  Sensitive Data Exposure  – Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.

Zend/Crypt/BlockCipher can be used to encrypt and decrypt all the sensitive data

7) Missing Function Level Access Control – Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization.

Zend\Permissions\Acl

The component provides a lightweight and flexible access control list (ACL) implementation for privileges management.

Zend\Permissions\Rbac

Provides a lightweight Role-Based Access Control implementation based around PHP 5.3’s SPL RecursiveIterator and RecursiveIteratorIterator

● RBAC differs from access control lists (ACL) by putting the emphasis on roles and their permissions rather than objects (resources).

8) Cross-Site Request Forgery (CSRF) – A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.

$form = new Form();
$form->addElement('hash', 'nohackers',
    array('salt' => 'STRONG SALT@#$'));
if ($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
    // Safe here
} else if (count($form->getErrors('request_token')) > 0) {

    ///Show him the error controller
    $this->_forward('csrf-forbidden', 'error');
    return;
}

Zend_Session_Namespace creates a unique id, and checks for it when submission (checking that the TTL has not expired). The ‘Identical’ validator is then used to ensure the submitted hash matches the stored hash. The ‘formHidden’ view helper is used to render the element in the form.

9) Using Components with Known Vulnerabilities – Components, such as libraries, frameworks, and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts.

10) Unvalidated Redirects and Forwards Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

 $redirect_url = $_GET['url'];
 header("Location: " . $redirect_url);

The above code takes URL from the input and without any validation it has sent to the redirection that is potentially a security issue. Before calling the header function the code has to validate with the preferred domain name.

The above mentioned 10 security flaws are top 10 of 2013.