Category: Security

Q: Prevent XSS attacking in Cakephp

To create CRUD actions is an easy thing in Cakephp. 

Now, I want to prevent XSS attacking in Cakephp (XSS headers?), how can I add this security feature to my application?

For example, creating an entity is easy (From the cookbook):

// src/Controller/ArticlesController.php

namespace App\Controller;

use App\Controller\AppController;

class ArticlesController extends AppController
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Flash'); // Include the FlashComponent
    }

    public function index()
    {
        $this->set('articles', $this->Articles->find('all'));
    }

    public function view($id)
    {
        $article = $this->Articles->get($id);
        $this->set(compact('article'));
    }

    public function add()
    {
        $article = $this->Articles->newEntity();
        if ($this->request->is('post')) {
            $article = $this->Articles->patchEntity($article, $this->request->data);
            if ($this->Articles->save($article)) {
                $this->Flash->success(__('Your article has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to add your article.'));
        }
        $this->set('article', $article);
    }
}

But I didn't see a way to prevent XSS attack.

xss
3 Answers

Version: 3

user
Lara

4

Use htmlspecialchars() or simply h() in CakePHP.

In short, use h() to sanitize data before rendering to view.

Article Title: <?= h($article['title']); ?>


$article['title'] = '<script>alert('attack');</script>';

output:

Article Title: &lt;script&gt;alert(&#039;attack&#039;);&lt;/script&gt;
Kristi
Kristi

137

Html elements are escaped by default within all HtmlHelpers unless you turn escape off. And remember you have to use

htmlspecialchars()

when you write a string to Html content.

set http headers

header("X-XSS-Protection: 0");
Ksmacky
Ksmacky

30

Created: 6 Oct '16

Last Reply: 7 Oct '16

Replies: 3

Views: 1275

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions