本文由腾讯WeTest团队提供,更多资讯可直接戳链接查看: http://wetest.qq.com/lab/微信号:TencentWeTest
对于新接触web开发的同学来说,XSS注入是一件非常头疼的事情。就算是web开发多年的老手,也不敢保证自己写的代码完全没有XSS注入的风险。
因为现在比较主流的XSS防治手段主要有两种,一种是在用户输入是将异常关键词过滤,另一种则是在页面渲染时将html内容实体化转义。
然而第一种方法一定程度上对业务数据要求相对较高,存在屏蔽数据和业务数据有冲突的情况,例如“程序类帮助文档的编辑保存”,“外站帖子爬虫”等等。都不能无差别将异常关键词过滤掉,必须保持原输入内容的完整性。
而另一种html内容实体化的方式,又非常的依赖开发的编程习惯。一个不小心漏写了就是一个安全工单,做web的前端同事应该深有体会。于是,我开始研究能不能不再依赖开发习惯,从框架层面上完全屏蔽XSS。
这里先介绍一下我的PHP web Server框架,是我自己从从事web开发开始就一直在维护更新的框架,链接在此,有兴趣的同学,可以看下。或者提出更多改进的建议。
首先来看下普通的PHP是怎么转义html实体的:
htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE)ENT_QUOTES 意思是需要转义双引号(”)和 单引号 (’)
ENT_SUBSTITUTE 意思是 把无效的编码替代成一个指定的带有 Unicode 替代字符
首先很容易想到的是把php模版中的字符串全部替换掉。
而熟悉smarty的同学应该知道,其实smarty的模版渲染也是用了转义字符串的方式。那我们渲染页面的代码可以这么写。
/*** 获得模板渲染后的内容* @return string*/public function getContent(){//防XSS注入foreach ( [Math Processing Error]
param) { [Math Processing Error]param) ? htmlspecialchars( [Math Processing Error]param;}unset($param);extract($this->params); ob_start(); //include template $file = sprintf('%s/template/%s.tpl.php', TXApp::$app_root, $this->view); include $file; $content = ob_get_clean(); return $content;}
这样的话,传入的字符串类型的变量都会被替换掉了。但是问题也很明显。那就是如果是数组或者object对象,里面的内容就无法进行转义了。而这同样也是smarty的一个弊端,smarty是在assign方法里进行的实体化转义,如果是数组或者object就无视了。当然我们还需要更进一步的进行转义处理。
有同学看到这里肯定会有个想法,如果是数组的话,递归进行转义处理不就可以了吗。
事实上我一开始的确是这么做的,但是弊端也很明显。递归的层数越多,性能损耗就越大。而且并非所有进行转义的内容我们都会用到,这样就会造成性能的浪费。最优化的处理方式就是当需要用到的时候再做转义处理,没用到的时候该咋样还是咋样。
于是我开始着手自己写一个类,在我的框架里我命名为TXArray 继承了ArrayObject,也就是让其具备了array的部分性质。接下来开始进行array 方法重构。以下是部分代码
class TXArray extends ArrayObject{private [Math Processing Error]
encodes = [];public function __construct($storage=array()){ $this->storage = $storage;}public function getIterator(){ foreach ($this->storage as $key => $value){ $key = $this->encode($key); if (!isset($this->encodes[$key])){ $this->encodes[$key] = $this->encode($value); } } return new ArrayIterator($this->encodes);}public function offsetGet($k){ if (isset($this->storage[$k])){ $key = $this->encode($k); if (!isset($this->encodes[$key])){ $this->encodes[$key] = $this->encode($this->storage[$k]); } return $this->encodes[$key]; } return null;}public function offsetExists($k){ return isset($this->storage[$k]);}public function offsetUnset($k){ unset($this->storage[$k]); $k = $this->encode($k); unset($this->encodes[$k]);}public function offsetSet($k, $value){ $this->storage[$k] = $value; $this->encodes[$k] = $this->encode($value);}public function count(){ return count($this->storage);}private function encode($value){ if (is_string($value)){ $value = is_string($value) ? htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE) : $value } elseif (is_array($value)){ $value = new self($value); } return $value;}
}offsetGet 会在 [Math Processing Error]
key] 时候被调用。getIterator() 方法则是在 foreach循环时被调用。当发现内部参数是个array时,会再次递归调用自己,重复上述步骤。效果如下图所示:这样一个递归的转义模型就写好了。也实现了用到时才转义的目标。
但是还有个问题。并不是所有字段都需要转义的,例如我们平台的舆情监控数据,数据来源主要是各大贴吧论坛,数据本身包含了图片img,字体颜色等html元素。在展示时并不希望被模版转义。所以我在框架上继续优化。添加了PHP的魔法方法__get()
public function __get($k){ return isset($this->storage[$k]) ? $this->storage[$k] : null;}public function get($key){ return $this->__get($key);}
也就是说只要调用 [Math Processing Error]
array->get(0) 就可以直接获取原来的数据而不进行转义了。另外看业务也再需要加上一些对array的处理方法,例如array_key_exists,in_array, join等。或者直接使用__call() 魔法方法
public function __call($method, $args){ $args[] = &$this->storage; return call_user_func_array($method, $args);}public function serialize(){ return serialize($this->storage);}public function __invoke(){ return $this->storage ? true : false;}public function keys(){ return array_keys($this->values(false));}
然后我们在页面模版里就可以愉快的使用了
但是这个TXArray还是有个问题,就是如果需要转化成json全部下发给js使用的话,那里面的数据就无法被转义了。当然也可以递归先全转义一遍,但总觉得代码不够漂亮。这个问题我还会继续研究。有新的进展和优化我都会上传到我的 PHP开源组件框架 中,大家有什么好的建议都可以rtx跟我探讨沟通哈
本文由腾讯WeTest团队提供,更多资讯可直接戳链接查看: http://wetest.qq.com/lab/微信号:TencentWeTest

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.