SecurityTest.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. <?php
  2. /* Copyright (C) 2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. * or see https://www.gnu.org/
  18. */
  19. /**
  20. * \file test/phpunit/SecurityTest.php
  21. * \ingroup test
  22. * \brief PHPUnit test
  23. * \remarks To run this script as CLI: phpunit filename.php
  24. */
  25. global $conf,$user,$langs,$db;
  26. //define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver
  27. //require_once 'PHPUnit/Autoload.php';
  28. if (! defined('NOREQUIRESOC')) {
  29. define('NOREQUIRESOC', '1');
  30. }
  31. if (! defined('NOCSRFCHECK')) {
  32. define('NOCSRFCHECK', '1');
  33. }
  34. if (! defined('NOTOKENRENEWAL')) {
  35. define('NOTOKENRENEWAL', '1');
  36. }
  37. if (! defined('NOREQUIREMENU')) {
  38. define('NOREQUIREMENU', '1'); // If there is no menu to show
  39. }
  40. if (! defined('NOREQUIREHTML')) {
  41. define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
  42. }
  43. if (! defined('NOREQUIREAJAX')) {
  44. define('NOREQUIREAJAX', '1');
  45. }
  46. if (! defined("NOLOGIN")) {
  47. define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
  48. }
  49. if (! defined("NOSESSION")) {
  50. define("NOSESSION", '1');
  51. }
  52. require_once dirname(__FILE__).'/../../htdocs/main.inc.php';
  53. require_once dirname(__FILE__).'/../../htdocs/core/lib/security.lib.php';
  54. require_once dirname(__FILE__).'/../../htdocs/core/lib/security2.lib.php';
  55. if (empty($user->id)) {
  56. print "Load permissions for admin user nb 1\n";
  57. $user->fetch(1);
  58. $user->getrights();
  59. }
  60. $conf->global->MAIN_DISABLE_ALL_MAILS=1;
  61. /**
  62. * Class for PHPUnit tests
  63. *
  64. * @backupGlobals disabled
  65. * @backupStaticAttributes enabled
  66. * @remarks backupGlobals must be disabled to have db,conf,user and lang not erased.
  67. */
  68. class SecurityTest extends PHPUnit\Framework\TestCase
  69. {
  70. protected $savconf;
  71. protected $savuser;
  72. protected $savlangs;
  73. protected $savdb;
  74. /**
  75. * Constructor
  76. * We save global variables into local variables
  77. *
  78. * @param string $name Name
  79. * @return SecurityTest
  80. */
  81. public function __construct($name = '')
  82. {
  83. parent::__construct($name);
  84. //$this->sharedFixture
  85. global $conf,$user,$langs,$db;
  86. $this->savconf=$conf;
  87. $this->savuser=$user;
  88. $this->savlangs=$langs;
  89. $this->savdb=$db;
  90. print __METHOD__." db->type=".$db->type." user->id=".$user->id;
  91. //print " - db ".$db->db;
  92. print "\n";
  93. }
  94. /**
  95. * setUpBeforeClass
  96. *
  97. * @return void
  98. */
  99. public static function setUpBeforeClass(): void
  100. {
  101. global $conf,$user,$langs,$db;
  102. $db->begin(); // This is to have all actions inside a transaction even if test launched without suite.
  103. print __METHOD__."\n";
  104. }
  105. /**
  106. * tearDownAfterClass
  107. *
  108. * @return void
  109. */
  110. public static function tearDownAfterClass(): void
  111. {
  112. global $conf,$user,$langs,$db;
  113. $db->rollback();
  114. // Restore value to a neutral value (it was set to a test value by some tests)
  115. unset($_SERVER["PHP_SELF"]);
  116. print __METHOD__."\n";
  117. }
  118. /**
  119. * Init phpunit tests
  120. *
  121. * @return void
  122. */
  123. protected function setUp(): void
  124. {
  125. global $conf,$user,$langs,$db;
  126. $conf=$this->savconf;
  127. $user=$this->savuser;
  128. $langs=$this->savlangs;
  129. $db=$this->savdb;
  130. print __METHOD__."\n";
  131. }
  132. /**
  133. * End phpunit tests
  134. *
  135. * @return void
  136. */
  137. protected function tearDown(): void
  138. {
  139. print __METHOD__."\n";
  140. }
  141. /**
  142. * testSetLang
  143. *
  144. * @return string
  145. */
  146. public function testSetLang()
  147. {
  148. global $conf;
  149. $conf=$this->savconf;
  150. $tmplangs = new Translate('', $conf);
  151. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = "' malicious text with quote";
  152. $tmplangs->setDefaultLang('auto');
  153. print __METHOD__.' $tmplangs->defaultlang='.$tmplangs->defaultlang."\n";
  154. $this->assertEquals($tmplangs->defaultlang, 'malicioustextwithquote_MALICIOUSTEXTWITHQUOTE');
  155. }
  156. /**
  157. * testSqlAndScriptInjectWithPHPUnit
  158. *
  159. * @return void
  160. */
  161. public function testSqlAndScriptInjectWithPHPUnit()
  162. {
  163. // Run tests
  164. // More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  165. // Should be OK
  166. $expectedresult=0;
  167. /*
  168. $test = '';
  169. $result=testSqlAndScriptInject($test, 0);
  170. $this->assertGreaterThanOrEqual(0, $result, 'Error on testSqlAndScriptInject kkk');
  171. */
  172. $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php';
  173. $result=testSqlAndScriptInject($_SERVER["PHP_SELF"], 2);
  174. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for PHP_SELF that should be ok');
  175. $test = 'This is a < inside string with < and > also and tag like <a> before the >';
  176. $result=testSqlAndScriptInject($test, 0);
  177. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject expected 0b');
  178. $test = 'This is the union of all for the selection of the best';
  179. $result=testSqlAndScriptInject($test, 0);
  180. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject expected 0c');
  181. $test='/user/perms.php?id=1&action=addrights&entity=1&rights=123&confirm=yes&token=123456789&updatedmodulename=lmscoursetracking';
  182. $result=testSqlAndScriptInject($test, 1);
  183. print "test=".$test." result=".$result."\n";
  184. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject with a valid url');
  185. // Should detect attack
  186. $expectedresult=1;
  187. $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php/<svg>';
  188. $result=testSqlAndScriptInject($_SERVER["PHP_SELF"], 2);
  189. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject for PHP_SELF that should detect XSS');
  190. $test = 'select @@version';
  191. $result=testSqlAndScriptInject($test, 0);
  192. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL1a. Should find an attack on POST param and did not.');
  193. $test = 'select @@version';
  194. $result=testSqlAndScriptInject($test, 1);
  195. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL1b. Should find an attack on GET param and did not.');
  196. $test = '... update ... set ... =';
  197. $result=testSqlAndScriptInject($test, 1);
  198. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL2a. Should find an attack on GET param and did not.');
  199. $test = "delete\nfrom";
  200. $result=testSqlAndScriptInject($test, 1);
  201. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL2b. Should find an attack on GET param and did not.');
  202. $test = 'action=update& ... set ... =';
  203. $result=testSqlAndScriptInject($test, 1);
  204. $this->assertEquals(0, $result, 'Error on testSqlAndScriptInject for SQL2b. Should not find an attack on GET param and did.');
  205. $test = '... union ... selection ';
  206. $result=testSqlAndScriptInject($test, 1);
  207. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL2c. Should find an attack on GET param and did not.');
  208. $test = 'j&#x61;vascript:';
  209. $result=testSqlAndScriptInject($test, 0);
  210. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for javascript1. Should find an attack and did not.');
  211. $test = 'j&#x61vascript:';
  212. $result=testSqlAndScriptInject($test, 0);
  213. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for javascript2. Should find an attack and did not.');
  214. $test = 'javascript&colon&#x3B;alert(1)';
  215. $result=testSqlAndScriptInject($test, 0);
  216. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for javascript2');
  217. $test="<img src='1.jpg' onerror =javascript:alert('XSS')>";
  218. $result=testSqlAndScriptInject($test, 0);
  219. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa1');
  220. $test="<img src='1.jpg' onerror =javascript:alert('XSS')>";
  221. $result=testSqlAndScriptInject($test, 2);
  222. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa2');
  223. $test='<IMG SRC=# onmouseover="alert(1)">';
  224. $result=testSqlAndScriptInject($test, 0);
  225. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa3');
  226. $test='<IMG SRC onmouseover="alert(1)">';
  227. $result=testSqlAndScriptInject($test, 0);
  228. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa4');
  229. $test='<IMG onmouseover="alert(1)">';
  230. $result=testSqlAndScriptInject($test, 0);
  231. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa5');
  232. $test='<IMG SRC=/ onerror="alert(1)">';
  233. $result=testSqlAndScriptInject($test, 0);
  234. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa6');
  235. $test='<IMG SRC=" &#14; javascript:alert(1);">';
  236. $result=testSqlAndScriptInject($test, 0);
  237. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa7');
  238. $test='<marquee onbeforeintput="alert(1)">';
  239. $result=testSqlAndScriptInject($test, 0);
  240. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject onbeforeintput');
  241. $test='<marquee onbounce="alert(1)">';
  242. $result=testSqlAndScriptInject($test, 0);
  243. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject onbounce');
  244. $test='<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>';
  245. $result=testSqlAndScriptInject($test, 0);
  246. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject bbb');
  247. $test='<SCRIPT SRC=http://xss.rocks/xss.js></SCRIPT>';
  248. $result=testSqlAndScriptInject($test, 0);
  249. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject ccc');
  250. $test='<IMG SRC="javascript:alert(\'XSS\');">';
  251. $result=testSqlAndScriptInject($test, 1);
  252. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject ddd');
  253. $test='<IMG """><SCRIPT>alert("XSS")</SCRIPT>">';
  254. $result=testSqlAndScriptInject($test, 0);
  255. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject eee');
  256. $test='<!-- Google analytics -->
  257. <script>
  258. (function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){
  259. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  260. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  261. })(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\');
  262. ga(\'create\',\'UA-99999999-9\', \'auto\');
  263. ga(\'send\', \'pageview\');
  264. </script>';
  265. $result=testSqlAndScriptInject($test, 0);
  266. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject eee');
  267. $test="<IMG SRC=\"jav\tascript:alert('XSS');\">"; // Is locked by some browser like chrome because the default directive no-referrer-when-downgrade is sent when requesting the SRC and then refused because of browser protection on img src load without referrer.
  268. $test="<IMG SRC=\"jav&#x0D;ascript:alert('XSS');\">"; // Same
  269. $test='<SCRIPT/XSS SRC="http://xss.rocks/xss.js"></SCRIPT>';
  270. $result=testSqlAndScriptInject($test, 0);
  271. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject fff1');
  272. $test='<SCRIPT/SRC="http://xss.rocks/xss.js"></SCRIPT>';
  273. $result=testSqlAndScriptInject($test, 0);
  274. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject fff2');
  275. // This case seems to be filtered by browsers now.
  276. $test='<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert(1)>';
  277. //$result=testSqlAndScriptInject($test, 0);
  278. //$this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject ggg');
  279. $test='<iframe src=http://xss.rocks/scriptlet.html <';
  280. $result=testSqlAndScriptInject($test, 0);
  281. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject hhh');
  282. $test='Set.constructor`alert\x281\x29```';
  283. $result=testSqlAndScriptInject($test, 0);
  284. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject iii');
  285. $test="on<!-- ab\nc -->error=alert(1)";
  286. $result=testSqlAndScriptInject($test, 0);
  287. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject jjj');
  288. $test="<img src=x one<a>rror=alert(document.location)";
  289. $result=testSqlAndScriptInject($test, 0);
  290. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject kkk');
  291. $test="<a onpointerdown=alert(document.domain)>XSS</a>";
  292. $result=testSqlAndScriptInject($test, 0);
  293. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject lll');
  294. $test='<a onscrollend=alert(1) style="display:block;overflow:auto;border:1px+dashed;width:500px;height:100px;"><br><br><br><br><br><span+id=x>test</span></a>'; // Add the char %F6 into the variable
  295. $result=testSqlAndScriptInject($test, 0);
  296. //print "test=".$test." result=".$result."\n";
  297. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject mmm');
  298. $test="Text with ' encoded with the numeric html entity converted into text entity &#39; (like when submited by CKEditor)";
  299. $result=testSqlAndScriptInject($test, 0); // result must be 0
  300. $this->assertEquals(0, $result, 'Error on testSqlAndScriptInject mmm, result should be 0 and is not');
  301. $test ='<a href="j&Tab;a&Tab;v&Tab;asc&NewLine;ri&Tab;pt:&lpar;a&Tab;l&Tab;e&Tab;r&Tab;t&Tab;(document.cookie)&rpar;">XSS</a>';
  302. $result=testSqlAndScriptInject($test, 0);
  303. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject nnn, result should be >= 1 and is not');
  304. $test="/dolibarr/htdocs/index.php/".chr('246')."abc"; // Add the char %F6 into the variable
  305. $result=testSqlAndScriptInject($test, 2);
  306. //print "test=".$test." result=".$result."\n";
  307. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject with a non valid UTF8 char');
  308. }
  309. /**
  310. * testGETPOST
  311. *
  312. * @return string
  313. */
  314. public function testGETPOST()
  315. {
  316. global $conf,$user,$langs,$db;
  317. $conf=$this->savconf;
  318. $user=$this->savuser;
  319. $langs=$this->savlangs;
  320. $db=$this->savdb;
  321. // Force default mode
  322. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 0;
  323. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY = 0;
  324. $conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES = 0;
  325. $conf->global->MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 0;
  326. $_COOKIE["id"]=111;
  327. $_POST["param0"]='A real string with <a href="rrr" title="aa&quot;bb">aaa</a> and " and \' and &amp; inside content';
  328. $_GET["param1"]="222";
  329. $_POST["param1"]="333";
  330. $_GET["param2"]='a/b#e(pr)qq-rr\cc';
  331. $_GET["param3"]='"&#110;a/b#e(pr)qq-rr\cc'; // Same than param2 + " and &#110;
  332. $_GET["param4a"]='..&#47;../dir';
  333. $_GET["param4b"]='..&#92;..\dirwindows';
  334. $_GET["param5"]="a_1-b";
  335. $_POST["param6"]="&quot;&gt;<svg o&#110;load='console.log(&quot;123&quot;)'&gt;";
  336. $_POST["param6b"]='<<<../>../>../svg><<<../>../>../animate =alert(1)>abc';
  337. $_GET["param7"]='"c:\this is a path~1\aaa&#110; &#x&#x31;&#x31;&#x30;;" abc<bad>def</bad>';
  338. $_POST["param8a"]="Hacker<svg o&#110;load='console.log(&quot;123&quot;)'"; // html tag is not closed so it is not detected as html tag but is still harmfull
  339. $_POST['param8b']='<img src=x onerror=alert(document.location) t='; // this is html obfuscated by non closing tag
  340. $_POST['param8c']='< with space after is ok';
  341. $_POST['param8d']='<abc123 is html to clean';
  342. $_POST['param8e']='<123abc is not html to clean'; // other similar case: '<2021-12-12'
  343. $_POST['param8f']='abc<<svg <><<animate onbegin=alert(document.domain) a';
  344. $_POST["param9"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'objnotdefined\'';
  345. $_POST["param10"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'<abc>objnotdefined\'';
  346. $_POST["param11"]=' Name <email@email.com> ';
  347. $_POST["param12"]='<!DOCTYPE html><html>aaa</html>';
  348. $_POST["param13"]='&#110; &#x6E; &gt; &lt; &quot; <a href=\"j&#x61;vascript:alert(document.domain)\">XSS</a>';
  349. $_POST["param13b"]='&#110; &#x6E; &gt; &lt; &quot; <a href=\"j&#x61vascript:alert(document.domain)\">XSS</a>';
  350. $_POST["param14"]="Text with ' encoded with the numeric html entity converted into text entity &#39; (like when submited by CKEditor)";
  351. $_POST["param15"]="<img onerror<=alert(document.domain)> src=>0xbeefed";
  352. //$_POST["param15b"]="<html><head><title>Example HTML</title></head><body><div><p>This is a paragraph.</div><ul><li>Item 1</li><li>Item 2</li></ol></body><html>";
  353. $_POST["param16"]='<a style="z-index: 1000">abc</a>';
  354. $_POST["param17"]='<span style="background-image: url(logout.php)">abc</span>';
  355. $_POST["param18"]='<span style="background-image: url(...?...action=aaa)">abc</span>';
  356. $_POST["param19"]='<a href="j&Tab;a&Tab;v&Tab;asc&NewLine;ri&Tab;pt:&lpar;alert(document.cookie)&rpar;">XSS</a>';
  357. //$_POST["param19"]='<a href="javascript:alert(document.cookie)">XSS</a>';
  358. $result=GETPOST('id', 'int'); // Must return nothing
  359. print __METHOD__." result=".$result."\n";
  360. $this->assertEquals('', $result);
  361. $result=GETPOST("param1", 'int');
  362. print __METHOD__." result=".$result."\n";
  363. $this->assertEquals(222, $result, 'Test on param1 with no 3rd param');
  364. $result=GETPOST("param1", 'int', 2);
  365. print __METHOD__." result=".$result."\n";
  366. $this->assertEquals(333, $result, 'Test on param1 with 3rd param = 2');
  367. // Test with alpha
  368. $result=GETPOST("param0", 'alpha'); // a simple format, so " completely removed
  369. $resultexpected = 'A real string with aaa and and \' and & inside content';
  370. print __METHOD__." result=".$result."\n";
  371. $this->assertEquals($resultexpected, $result, 'Test on param0');
  372. $result=GETPOST("param2", 'alpha');
  373. print __METHOD__." result=".$result."\n";
  374. $this->assertEquals($result, $_GET["param2"], 'Test on param2');
  375. $result=GETPOST("param3", 'alpha'); // Must return string sanitized from char "
  376. print __METHOD__." result=".$result."\n";
  377. $this->assertEquals($result, 'na/b#e(pr)qq-rr\cc', 'Test on param3');
  378. $result=GETPOST("param4a", 'alpha'); // Must return string sanitized from ../
  379. print __METHOD__." result=".$result."\n";
  380. $this->assertEquals($result, 'dir');
  381. $result=GETPOST("param4b", 'alpha'); // Must return string sanitized from ../
  382. print __METHOD__." result=".$result."\n";
  383. $this->assertEquals($result, 'dirwindows');
  384. // Test with aZ09
  385. $result=GETPOST("param1", 'aZ09');
  386. print __METHOD__." result=".$result."\n";
  387. $this->assertEquals($result, $_GET["param1"]);
  388. $result=GETPOST("param2", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  389. print __METHOD__." result=".$result."\n";
  390. $this->assertEquals($result, '');
  391. $result=GETPOST("param3", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  392. print __METHOD__." result=".$result."\n";
  393. $this->assertEquals($result, '');
  394. $result=GETPOST("param4a", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  395. print __METHOD__." result=".$result."\n";
  396. $this->assertEquals('', $result);
  397. $result=GETPOST("param4b", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  398. print __METHOD__." result=".$result."\n";
  399. $this->assertEquals('', $result);
  400. $result=GETPOST("param5", 'aZ09');
  401. print __METHOD__." result=".$result."\n";
  402. $this->assertEquals($_GET["param5"], $result);
  403. // Test with nohtml
  404. $result=GETPOST("param6", 'nohtml');
  405. print __METHOD__." result6=".$result."\n";
  406. $this->assertEquals('">', $result);
  407. // Test with alpha = alphanohtml. We must convert the html entities like &#110; and disable all entities
  408. $result=GETPOST("param6", 'alphanohtml');
  409. print __METHOD__." result=".$result."\n";
  410. $this->assertEquals('>', $result);
  411. $result=GETPOST("param6b", 'alphanohtml');
  412. print __METHOD__." result=".$result."\n";
  413. $this->assertEquals('abc', $result);
  414. $result=GETPOST("param8a", 'alphanohtml');
  415. print __METHOD__." result=".$result."\n";
  416. $this->assertEquals("Hackersvg onload='console.log(123)'", $result);
  417. $result=GETPOST("param8b", 'alphanohtml');
  418. print __METHOD__." result=".$result."\n";
  419. $this->assertEquals('img src=x onerror=alert(document.location) t=', $result, 'Test a string with non closing html tag with alphanohtml');
  420. $result=GETPOST("param8c", 'alphanohtml');
  421. print __METHOD__." result=".$result."\n";
  422. $this->assertEquals($_POST['param8c'], $result, 'Test a string with non closing html tag with alphanohtml');
  423. $result=GETPOST("param8d", 'alphanohtml');
  424. print __METHOD__." result=".$result."\n";
  425. $this->assertEquals('abc123 is html to clean', $result, 'Test a string with non closing html tag with alphanohtml');
  426. $result=GETPOST("param8e", 'alphanohtml');
  427. print __METHOD__." result=".$result."\n";
  428. $this->assertEquals($_POST['param8e'], $result, 'Test a string with non closing html tag with alphanohtml');
  429. $result=GETPOST("param8f", 'alphanohtml');
  430. print __METHOD__." result=".$result."\n";
  431. $this->assertEquals('abcsvg animate onbegin=alert(document.domain) a', $result, 'Test a string with html tag open with several <');
  432. $result=GETPOST("param9", 'alphanohtml');
  433. print __METHOD__." result=".$result."\n";
  434. $this->assertEquals($_POST["param9"], $result);
  435. $result=GETPOST("param10", 'alphanohtml');
  436. print __METHOD__." result=".$result."\n";
  437. $this->assertEquals($_POST["param9"], $result, 'We should get param9 after processing param10');
  438. $result=GETPOST("param11", 'alphanohtml');
  439. print __METHOD__." result=".$result."\n";
  440. $this->assertEquals("Name", $result, 'Test an email string with alphanohtml');
  441. $result=GETPOST("param13", 'alphanohtml');
  442. print __METHOD__." result=".$result."\n";
  443. $this->assertEquals('n n > < XSS', $result, 'Test that html entities are decoded with alpha');
  444. // Test with alphawithlgt
  445. $result=GETPOST("param11", 'alphawithlgt');
  446. print __METHOD__." result=".$result."\n";
  447. $this->assertEquals(trim($_POST["param11"]), $result, 'Test an email string with alphawithlgt');
  448. // Test with restricthtml: we must remove html open/close tag and content but not htmlentities (we can decode html entities for ascii chars like &#110;)
  449. $result=GETPOST("param0", 'restricthtml');
  450. $resultexpected = 'A real string with <a href="rrr" title="aa&quot;bb">aaa</a> and " and \' and &amp; inside content';
  451. print __METHOD__." result=".$result."\n";
  452. $this->assertEquals($resultexpected, $result, 'Test on param0');
  453. $result=GETPOST("param6", 'restricthtml');
  454. print __METHOD__." result for param6=".$result." - before=".$_POST["param6"]."\n";
  455. $this->assertEquals('&quot;&gt;', $result);
  456. $result=GETPOST("param7", 'restricthtml');
  457. print __METHOD__." result param7 = ".$result."\n";
  458. $this->assertEquals('"c:\this is a path~1\aaan &#x;;;;" abcdef', $result);
  459. $result=GETPOST("param8e", 'restricthtml');
  460. print __METHOD__." result param8e = ".$result."\n";
  461. $this->assertEquals('', $result);
  462. $result=GETPOST("param12", 'restricthtml');
  463. print __METHOD__." result=".$result."\n";
  464. $this->assertEquals(trim($_POST["param12"]), $result, 'Test a string with DOCTYPE and restricthtml');
  465. $result=GETPOST("param13", 'restricthtml');
  466. print __METHOD__." result=".$result."\n";
  467. $this->assertEquals('n n &gt; &lt; &quot; <a href=\"alert(document.domain)\">XSS</a>', $result, 'Test 13 that HTML entities are decoded with restricthtml, but only for common alpha chars');
  468. $result=GETPOST("param13b", 'restricthtml');
  469. print __METHOD__." result=".$result."\n";
  470. $this->assertEquals('n n &gt; &lt; &quot; <a href=\"alert(document.domain)\">XSS</a>', $result, 'Test 13b that HTML entities are decoded with restricthtml, but only for common alpha chars');
  471. $result=GETPOST("param14", 'restricthtml');
  472. print __METHOD__." result=".$result."\n";
  473. $this->assertEquals("Text with ' encoded with the numeric html entity converted into text entity &#39; (like when submited by CKEditor)", $result, 'Test 14');
  474. $result=GETPOST("param15", 'restricthtml'); // param15 = <img onerror<=alert(document.domain)> src=>0xbeefed that is a dangerous string
  475. print __METHOD__." result=".$result."\n";
  476. $this->assertEquals("<img onerror=alert(document.domain) src=>0xbeefed", $result, 'Test 15'); // The GETPOST return a harmull string
  477. $result=GETPOST("param19", 'restricthtml');
  478. print __METHOD__." result=".$result."\n";
  479. $this->assertEquals('<a href="&lpar;alert(document.cookie)&rpar;">XSS</a>', $result, 'Test 19');
  480. // Test with restricthtml + MAIN_RESTRICTHTML_ONLY_VALID_HTML only to test disabling of bad atrributes
  481. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 1;
  482. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY = 0;
  483. //$_POST["param0"] = 'A real string with <a href="rrr" title="aabb">aaa</a> and " inside content';
  484. $result=GETPOST("param0", 'restricthtml');
  485. $resultexpected = 'A real string with <a href="rrr" title=\'aa"bb\'>aaa</a> and " and \' and &amp; inside content';
  486. print __METHOD__." result for param0=".$result."\n";
  487. $this->assertEquals($resultexpected, $result, 'Test on param0');
  488. $result=GETPOST("param15", 'restricthtml'); // param15 = <img onerror<=alert(document.domain)> src=>0xbeefed that is a dangerous string
  489. print __METHOD__." result for param15=".$result."\n";
  490. //$this->assertEquals('InvalidHTMLStringCantBeCleaned', $result, 'Test 15b'); // With some PHP and libxml version, we got this result when parsing invalid HTML, but ...
  491. //$this->assertEquals('<img onerror> src=&gt;0xbeefed', $result, 'Test 15b'); // ... on other PHP and libxml versions, we got a HTML that has been cleaned
  492. $result=GETPOST("param6", 'restricthtml'); // param6 = "&quot;&gt;<svg o&#110;load='console.log(&quot;123&quot;)'&gt;"
  493. print __METHOD__." result for param6=".$result." - before=".$_POST["param6"]."\n";
  494. //$this->assertEquals('InvalidHTMLStringCantBeCleaned', $result, 'Test 15b'); // With some PHP and libxml version, we got this result when parsing invalid HTML, but ...
  495. //$this->assertEquals('"&gt;', $result); // ... on other PHP and libxml versions, we got a HTML that has been cleaned
  496. $result=GETPOST("param7", 'restricthtml'); // param7 = "c:\this is a path~1\aaa&#110; &#x&#x31;&#x31;&#x30;;" abc<bad>def</bad>
  497. print __METHOD__." result param7 = ".$result."\n";
  498. //$this->assertEquals('InvalidHTMLStringCantBeCleaned', $result, 'Test 15b'); // With some PHP and libxml version, we got this result when parsing invalid HTML, but ...
  499. //$this->assertEquals('"c:\this is a path~1\aaan 110;" abcdef', $result); // ... on other PHP and libxml versions, we got a HTML that has been cleaned
  500. // Test with restricthtml + MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY only to test disabling of bad atrributes
  501. if (extension_loaded('tidy') && class_exists("tidy")) {
  502. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 0;
  503. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY = 1;
  504. $result=GETPOST("param0", 'restricthtml');
  505. $resultexpected = 'A real string with <a href="rrr" title="aa&quot;bb">aaa</a> and " and \' and & inside content';
  506. print __METHOD__." result for param0=".$result."\n";
  507. $this->assertEquals($resultexpected, $result, 'Test on param0');
  508. $result=GETPOST("param15", 'restricthtml'); // param15 = <img onerror<=alert(document.domain)> src=>0xbeefed that is a dangerous string
  509. print __METHOD__." result=".$result."\n";
  510. $result=GETPOST("param6", 'restricthtml');
  511. print __METHOD__." result for param6=".$result." - before=".$_POST["param6"]."\n";
  512. $this->assertEquals('"&gt;', $result);
  513. $result=GETPOST("param7", 'restricthtml');
  514. print __METHOD__." result param7 = ".$result."\n";
  515. $this->assertEquals('"c:\this is a path~1\aaan &amp;#x110;" abcdef', $result);
  516. }
  517. // Test with restricthtml + MAIN_RESTRICTHTML_ONLY_VALID_HTML + MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY to test disabling of bad atrributes
  518. if (extension_loaded('tidy') && class_exists("tidy")) {
  519. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 1;
  520. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY = 1;
  521. $result=GETPOST("param0", 'restricthtml');
  522. $resultexpected = 'A real string with <a href="rrr" title=\'aa"bb\'>aaa</a> and " and \' and & inside content';
  523. print __METHOD__." result for param0=".$result."\n";
  524. $this->assertEquals($resultexpected, $result, 'Test on param0');
  525. $result=GETPOST("param15", 'restricthtml'); // param15 = <img onerror<=alert(document.domain)> src=>0xbeefed that is a dangerous string
  526. print __METHOD__." result=".$result."\n";
  527. $result=GETPOST("param6", 'restricthtml');
  528. print __METHOD__." result for param6=".$result." - before=".$_POST["param6"]."\n";
  529. $this->assertEquals('"&gt;', $result);
  530. $result=GETPOST("param7", 'restricthtml');
  531. print __METHOD__." result param7 = ".$result."\n";
  532. $this->assertEquals('"c:\this is a path~1\aaan 110;" abcdef', $result);
  533. }
  534. // Test with restricthtml + MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES to test disabling of bad atrributes
  535. unset($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML);
  536. unset($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY);
  537. $conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES = 1;
  538. $result=GETPOST("param15", 'restricthtml');
  539. print __METHOD__." result=".$result."\n";
  540. $this->assertEquals('<img src="">0xbeefed', $result, 'Test 15c');
  541. $result=GETPOST('param16', 'restricthtml');
  542. print __METHOD__." result=".$result."\n";
  543. $this->assertEquals('<a style=" 1000">abc</a>', $result, 'Test tag a with forbidden attribute z-index');
  544. $result=GETPOST('param17', 'restricthtml');
  545. print __METHOD__." result=".$result."\n";
  546. $this->assertEquals('<span style="background-image: url()">abc</span>', $result, 'Test anytag with a forbidden value for attribute');
  547. $result=GETPOST('param18', 'restricthtml');
  548. print __METHOD__." result=".$result."\n";
  549. $this->assertEquals('<span style="background-image: url(...?...aaa)">abc</span>', $result, 'Test anytag with a forbidden value for attribute');
  550. unset($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES);
  551. // Special test for GETPOST of backtopage, backtolist or backtourl parameter
  552. $_POST["backtopage"]='//www.google.com';
  553. $result=GETPOST("backtopage");
  554. print __METHOD__." result=".$result."\n";
  555. $this->assertEquals('www.google.com', $result, 'Test for backtopage param');
  556. $_POST["backtopage"]='https:https://www.google.com';
  557. $result=GETPOST("backtopage");
  558. print __METHOD__." result=".$result."\n";
  559. $this->assertEquals('www.google.com', $result, 'Test for backtopage param');
  560. $_POST["backtolist"]='::HTTPS://www.google.com';
  561. $result=GETPOST("backtolist");
  562. print __METHOD__." result=".$result."\n";
  563. $this->assertEquals('www.google.com', $result, 'Test for backtopage param');
  564. $_POST["backtopage"]='http:www.google.com';
  565. $result=GETPOST("backtopage");
  566. print __METHOD__." result=".$result."\n";
  567. $this->assertEquals('httpwww.google.com', $result, 'Test for backtopage param');
  568. $_POST["backtopage"]='/mydir/mypage.php?aa=a%10a';
  569. $result=GETPOST("backtopage");
  570. print __METHOD__." result=".$result."\n";
  571. $this->assertEquals('/mydir/mypage.php?aa=a%10a', $result, 'Test for backtopage param');
  572. $_POST["backtopage"]='javascripT&javascript#javascriptxjavascript3a alert(1)';
  573. $result=GETPOST("backtopage");
  574. print __METHOD__." result=".$result."\n";
  575. $this->assertEquals('x3aalert(1)', $result, 'Test for backtopage param');
  576. $conf->global->MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT = 3;
  577. $_POST["pagecontentwithlinks"]='<img src="aaa"><img src="bbb"><img src="/ccc"><span style="background: url(/ddd)"></span>';
  578. $result=GETPOST("pagecontentwithlinks", 'restricthtml');
  579. print __METHOD__." result=".$result."\n";
  580. $this->assertEquals('ErrorTooManyLinksIntoHTMLString', $result, 'Test on limit on GETPOST fails');
  581. // Test that img src="data:..." is excluded from the count of external links
  582. $conf->global->MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT = 3;
  583. $_POST["pagecontentwithlinks"]='<img src="data:abc"><img src="bbb"><img src="/ccc"><span style="background: url(/ddd)"></span>';
  584. $result=GETPOST("pagecontentwithlinks", 'restricthtml');
  585. print __METHOD__." result=".$result."\n";
  586. $this->assertEquals('<img src="data:abc"><img src="bbb"><img src="/ccc"><span style="background: url(/ddd)"></span>', $result, 'Test on limit on GETPOST fails');
  587. $conf->global->MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 2;
  588. // Test that no links is allowed
  589. $_POST["pagecontentwithlinks"]='<img src="data:abc"><img src="bbb"><img src="/ccc"><span style="background: url(/ddd)"></span>';
  590. $result=GETPOST("pagecontentwithlinks", 'restricthtml');
  591. print __METHOD__." result=".$result."\n";
  592. $this->assertEquals('ErrorHTMLLinksNotAllowed', $result, 'Test on limit on MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 2 (no links allowed)');
  593. $conf->global->MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 1;
  594. // Test that links on wrapper or local url are allowed
  595. $_POST["pagecontentwithnowrapperlinks"]='<img src="data:abc"><img src="bbb"><img src="/ccc"><span style="background: url(/ddd)"></span>';
  596. $result=GETPOST("pagecontentwithnowrapperlinks", 'restricthtml');
  597. print __METHOD__." result=".$result."\n";
  598. $this->assertEquals('<img src="data:abc"><img src="bbb"><img src="/ccc"><span style="background: url(/ddd)"></span>', $result, 'Test on MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 1 (links on data or relative links ar allowed)');
  599. // Test that links not on wrapper and not data are disallowed
  600. $_POST["pagecontentwithnowrapperlinks"]='<img src="https://aaa">';
  601. $result=GETPOST("pagecontentwithnowrapperlinks", 'restricthtml');
  602. print __METHOD__." result=".$result."\n";
  603. $this->assertEquals('ErrorHTMLExternalLinksNotAllowed', $result, 'Test on MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 1 (no links to http allowed)');
  604. // Test that links not on wrapper and not data are disallowed
  605. $_POST["pagecontentwithnowrapperlinks"]='<span style="background: url(http://ddd)"></span>';
  606. $result=GETPOST("pagecontentwithnowrapperlinks", 'restricthtml');
  607. print __METHOD__." result=".$result."\n";
  608. $this->assertEquals('ErrorHTMLExternalLinksNotAllowed', $result, 'Test on MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 1 (no links to http allowed)');
  609. return $result;
  610. }
  611. /**
  612. * testEncodeDecode
  613. *
  614. * @return int
  615. */
  616. public function testEncodeDecode()
  617. {
  618. $stringtotest="This is a string to test encode/decode. This is a string to test encode/decode. This is a string to test encode/decode.";
  619. $encodedstring=dol_encode($stringtotest);
  620. $decodedstring=dol_decode($encodedstring);
  621. print __METHOD__." encodedstring=".$encodedstring." ".base64_encode($stringtotest)."\n";
  622. $this->assertEquals($stringtotest, $decodedstring, 'Use dol_encode/decode with no parameter');
  623. $encodedstring=dol_encode($stringtotest, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
  624. $decodedstring=dol_decode($encodedstring, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
  625. print __METHOD__." encodedstring=".$encodedstring." ".base64_encode($stringtotest)."\n";
  626. $this->assertEquals($stringtotest, $decodedstring, 'Use dol_encode/decode with a key parameter');
  627. return 0;
  628. }
  629. /**
  630. * testDolStringOnlyTheseHtmlTags
  631. *
  632. * @return int
  633. */
  634. public function testDolHTMLEntityDecode()
  635. {
  636. $stringtotest = 'a &colon; b &quot; c &#039; d &apos; e &eacute;';
  637. $decodedstring = dol_html_entity_decode($stringtotest, ENT_QUOTES);
  638. $this->assertEquals('a &colon; b " c \' d &apos; e é', $decodedstring, 'Function did not sanitize correclty');
  639. $stringtotest = 'a &colon; b &quot; c &#039; d &apos; e &eacute;';
  640. $decodedstring = dol_html_entity_decode($stringtotest, ENT_QUOTES|ENT_HTML5);
  641. $this->assertEquals('a : b " c \' d \' e é', $decodedstring, 'Function did not sanitize correclty');
  642. return 0;
  643. }
  644. /**
  645. * testDolStringOnlyTheseHtmlTags
  646. *
  647. * @return int
  648. */
  649. public function testDolStringOnlyTheseHtmlTags()
  650. {
  651. $stringtotest = '<a href="javascript:aaa">bbbڴ';
  652. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1);
  653. $this->assertEquals('<a href="aaa">bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 1');
  654. $stringtotest = '<a href="java'.chr(0).'script:aaa">bbbڴ';
  655. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1);
  656. $this->assertEquals('<a href="aaa">bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 2');
  657. $stringtotest = '<a href="javascript&colon;aaa">bbbڴ';
  658. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1);
  659. $this->assertEquals('<a href="aaa">bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 3');
  660. $stringtotest = 'text <link href="aaa"> text';
  661. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1, 0, array(), 0);
  662. $this->assertEquals('text text', $decodedstring, 'Function did not sanitize correclty with test 4a');
  663. $stringtotest = 'text <link href="aaa"> text';
  664. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1, 0, array(), 1);
  665. $this->assertEquals('text <link href="aaa"> text', $decodedstring, 'Function did not sanitize correclty with test 4b');
  666. return 0;
  667. }
  668. /**
  669. * testDolStringOnlyTheseHtmlAttributes
  670. *
  671. * @return int
  672. */
  673. public function testDolStringOnlyTheseHtmlAttributes()
  674. {
  675. $stringtotest = 'eée';
  676. $decodedstring = dol_string_onlythesehtmlattributes($stringtotest);
  677. $this->assertEquals('e&eacute;e', $decodedstring, 'Function did not sanitize correclty with test 1');
  678. $stringtotest = '<div onload="ee"><a href="123"><span class="abc">abc</span></a></div>';
  679. $decodedstring = dol_string_onlythesehtmlattributes($stringtotest);
  680. $decodedstring = preg_replace("/\n$/", "", $decodedstring);
  681. $this->assertEquals('<div><a href="123"><span class="abc">abc</span></a></div>', $decodedstring, 'Function did not sanitize correclty with test 2');
  682. return 0;
  683. }
  684. /**
  685. * testGetRandomPassword
  686. *
  687. * @return int
  688. */
  689. public function testGetRandomPassword()
  690. {
  691. global $conf;
  692. $genpass1=getRandomPassword(true); // Should be a string return by dol_hash (if no option set, will be md5)
  693. print __METHOD__." genpass1=".$genpass1."\n";
  694. $this->assertEquals(strlen($genpass1), 32);
  695. $genpass1=getRandomPassword(true, array('I')); // Should be a string return by dol_hash (if no option set, will be md5)
  696. print __METHOD__." genpass1=".$genpass1."\n";
  697. $this->assertEquals(strlen($genpass1), 32);
  698. $conf->global->USER_PASSWORD_GENERATED='None';
  699. $genpass2=getRandomPassword(false); // Should return an empty string
  700. print __METHOD__." genpass2=".$genpass2."\n";
  701. $this->assertEquals($genpass2, '');
  702. $conf->global->USER_PASSWORD_GENERATED='Standard';
  703. $genpass3=getRandomPassword(false); // Should return a password of 12 chars
  704. print __METHOD__." genpass3=".$genpass3."\n";
  705. $this->assertEquals(strlen($genpass3), 12);
  706. return 0;
  707. }
  708. /**
  709. * testRestrictedArea
  710. *
  711. * @return void
  712. */
  713. public function testRestrictedArea()
  714. {
  715. global $conf,$user,$langs,$db;
  716. $conf=$this->savconf;
  717. $user=$this->savuser;
  718. $langs=$this->savlangs;
  719. $db=$this->savdb;
  720. //$dummyuser=new User($db);
  721. //$result=restrictedArea($dummyuser,'societe');
  722. $result=restrictedArea($user, 'societe');
  723. $this->assertEquals(1, $result);
  724. }
  725. /**
  726. * testGetRandomPassword
  727. *
  728. * @return int
  729. */
  730. public function testGetURLContent()
  731. {
  732. global $conf;
  733. include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  734. $url = 'ftp://mydomain.com';
  735. $tmp = getURLContent($url);
  736. print __METHOD__." url=".$url."\n";
  737. $this->assertGreaterThan(0, strpos($tmp['curl_error_msg'], 'not supported')); // Test error if return does not contains 'not supported'
  738. $url = 'https://www.dolibarr.fr'; // This is a redirect 301 page
  739. $tmp = getURLContent($url, 'GET', '', 0); // We do NOT follow
  740. print __METHOD__." url=".$url."\n";
  741. $this->assertEquals(301, $tmp['http_code'], 'Should GET url 301 response and stop here');
  742. $url = 'https://www.dolibarr.fr'; // This is a redirect 301 page
  743. $tmp = getURLContent($url); // We DO follow a page with return 300 so result should be 200
  744. print __METHOD__." url=".$url."\n";
  745. $this->assertEquals(200, $tmp['http_code'], 'Should GET url 301 with a follow -> 200 but we get '.$tmp['http_code']);
  746. $url = 'http://localhost';
  747. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  748. print __METHOD__." url=".$url."\n";
  749. $this->assertEquals(400, $tmp['http_code'], 'Should GET url to '.$url.' that resolves to a local URL'); // Test we receive an error because localtest.me is not an external URL
  750. $url = 'http://127.0.0.1';
  751. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  752. print __METHOD__." url=".$url."\n";
  753. $this->assertEquals(400, $tmp['http_code'], 'Should GET url to '.$url.' that is a local URL'); // Test we receive an error because 127.0.0.1 is not an external URL
  754. $url = 'http://127.0.2.1';
  755. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  756. print __METHOD__." url=".$url."\n";
  757. $this->assertEquals(400, $tmp['http_code'], 'Should GET url to '.$url.' that is a local URL'); // Test we receive an error because 127.0.2.1 is not an external URL
  758. $url = 'https://169.254.0.1';
  759. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  760. print __METHOD__." url=".$url."\n";
  761. $this->assertEquals(400, $tmp['http_code'], 'Should GET url to '.$url.' that is a local URL'); // Test we receive an error because 169.254.0.1 is not an external URL
  762. $url = 'http://[::1]';
  763. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  764. print __METHOD__." url=".$url."\n";
  765. $this->assertEquals(400, $tmp['http_code'], 'Should GET url to '.$url.' that is a local URL'); // Test we receive an error because [::1] is not an external URL
  766. /*$url = 'localtest.me';
  767. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  768. print __METHOD__." url=".$url."\n";
  769. $this->assertEquals(400, $tmp['http_code'], 'Should GET url to '.$url.' that resolves to a local URL'); // Test we receive an error because localtest.me is not an external URL
  770. */
  771. $url = 'http://192.0.0.192';
  772. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL but on an IP in blacklist
  773. print __METHOD__." url=".$url." tmp['http_code'] = ".$tmp['http_code']."\n";
  774. $this->assertEquals(400, $tmp['http_code'], 'Access should be refused and was not'); // Test we receive an error because ip is in blacklist
  775. return 0;
  776. }
  777. /**
  778. * testDolSanitizeUrl
  779. *
  780. * @return void
  781. */
  782. public function testDolSanitizeUrl()
  783. {
  784. global $conf,$user,$langs,$db;
  785. $conf=$this->savconf;
  786. $user=$this->savuser;
  787. $langs=$this->savlangs;
  788. $db=$this->savdb;
  789. $test = 'javascripT&javascript#x3a alert(1)';
  790. $result=dol_sanitizeUrl($test);
  791. $this->assertEquals('x3a alert(1)', $result, 'Test on dol_sanitizeUrl A');
  792. $test = 'javajavascriptscript&cjavascriptolon;alert(1)';
  793. $result=dol_sanitizeUrl($test);
  794. $this->assertEquals('alert(1)', $result, 'Test on dol_sanitizeUrl B');
  795. $test = '/javas:cript/google.com';
  796. $result=dol_sanitizeUrl($test);
  797. $this->assertEquals('google.com', $result, 'Test on dol_sanitizeUrl C');
  798. }
  799. /**
  800. * testDolSanitizeEmail
  801. *
  802. * @return void
  803. */
  804. public function testDolSanitizeEmail()
  805. {
  806. global $conf,$user,$langs,$db;
  807. $conf=$this->savconf;
  808. $user=$this->savuser;
  809. $langs=$this->savlangs;
  810. $db=$this->savdb;
  811. $test = 'aaa@mycompany.com <My name>, bbb@mycompany.com <Another name>';
  812. $result=dol_sanitizeEmail($test);
  813. $this->assertEquals($test, $result, 'Test on dol_sanitizeEmail A');
  814. $test = "aaa@mycompany.com <My name>,\nbbb@mycompany.com <Another name>";
  815. $result=dol_sanitizeEmail($test);
  816. $this->assertEquals('aaa@mycompany.com <My name>,bbb@mycompany.com <Another name>', $result, 'Test on dol_sanitizeEmail B');
  817. $test = 'aaa@mycompany.com <My name>,\nbbb@mycompany.com <Another name>';
  818. $result=dol_sanitizeEmail($test);
  819. $this->assertEquals('aaa@mycompany.com <My name>,nbbb@mycompany.com <Another name>', $result, 'Test on dol_sanitizeEmail C');
  820. $test = 'aaa@mycompany.com <My name>, "bcc:bbb"@mycompany.com <Another name>';
  821. $result=dol_sanitizeEmail($test);
  822. $this->assertEquals('aaa@mycompany.com <My name>, bccbbb@mycompany.com <Another name>', $result, 'Test on dol_sanitizeEmail D');
  823. }
  824. /**
  825. * testDolSanitizeFileName
  826. *
  827. * @return void
  828. */
  829. public function testDolSanitizeFileName()
  830. {
  831. global $conf,$user,$langs,$db;
  832. $conf=$this->savconf;
  833. $user=$this->savuser;
  834. $langs=$this->savlangs;
  835. $db=$this->savdb;
  836. //$dummyuser=new User($db);
  837. //$result=restrictedArea($dummyuser,'societe');
  838. $result=dol_sanitizeFileName('bad file | evilaction');
  839. $this->assertEquals('bad file _ evilaction', $result);
  840. $result=dol_sanitizeFileName('bad file -evilparam --evilparam ---evilparam ----evilparam');
  841. $this->assertEquals('bad file _evilparam _evilparam _evilparam _evilparam', $result);
  842. }
  843. /**
  844. * testDolEval
  845. *
  846. * @return void
  847. */
  848. public function testDolEval()
  849. {
  850. global $conf,$user,$langs,$db;
  851. $conf=$this->savconf;
  852. $user=$this->savuser;
  853. $langs=$this->savlangs;
  854. $db=$this->savdb;
  855. // Declare classes found into string to evaluate
  856. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  857. include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  858. $result=dol_eval('1==1', 1, 0);
  859. print "result1 = ".$result."\n";
  860. $this->assertTrue($result);
  861. $result=dol_eval('1==2', 1, 0);
  862. print "result2 = ".$result."\n";
  863. $this->assertFalse($result);
  864. $s = '((($reloadedobj = new ClassThatDoesNotExists($db)) && ($reloadedobj->fetchNoCompute($objectoffield->fk_product) > 0)) ? \'1\' : \'0\')';
  865. $result3a = dol_eval($s, 1, 1, '2');
  866. print "result3a = ".$result."\n";
  867. $this->assertTrue(is_null($result3a));
  868. $s = '((($reloadedobj = new Project($db)) && ($reloadedobj->fetchNoCompute($objectoffield->fk_product) > 0)) ? \'1\' : \'0\')';
  869. $result3b = dol_eval($s, 1, 1, '2');
  870. print "result3b = ".$result."\n";
  871. $this->assertEquals('0', $result3b);
  872. $s = '(($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"';
  873. $result = (string) dol_eval($s, 1, 1, '2');
  874. print "result3 = ".$result."\n";
  875. $this->assertEquals('Parent project not found', $result);
  876. $s = '(($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : \'Parent project not found\'';
  877. $result = (string) dol_eval($s, 1, 1, '2');
  878. print "result4 = ".$result."\n";
  879. $this->assertEquals('Parent project not found', $result);
  880. $s = 'new abc->invoke(\'whoami\')';
  881. $result = (string) dol_eval($s, 1, 1, '2');
  882. print "result = ".$result."\n";
  883. $this->assertEquals('Bad string syntax to evaluate: new abc__forbiddenstring__(\'whoami\')', $result);
  884. $s = 'new ReflectionFunction(\'abc\')';
  885. $result = (string) dol_eval($s, 1, 1, '2');
  886. print "result = ".$result."\n";
  887. $this->assertEquals('Bad string syntax to evaluate: new __forbiddenstring__(\'abc\')', $result);
  888. $result = (string) dol_eval('$a=function() { }; $a;', 1, 1, '0');
  889. print "result5 = ".$result."\n";
  890. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  891. $result = (string) dol_eval('$a=function() { }; $a;', 1, 1, '1');
  892. print "result6 = ".$result."\n";
  893. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  894. $result = (string) dol_eval('$a=exec("ls");', 1, 1);
  895. print "result7 = ".$result."\n";
  896. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  897. $result = (string) dol_eval('$a=exec ("ls")', 1, 1);
  898. print "result8 = ".$result."\n";
  899. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  900. $result = (string) dol_eval('$a="test"; $$a;', 1, 0);
  901. print "result9 = ".$result."\n";
  902. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  903. $result = (string) dol_eval('`ls`', 1, 0);
  904. print "result10 = ".$result."\n";
  905. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  906. $result = (string) dol_eval("('ex'.'ec')('echo abc')", 1, 0);
  907. print "result11 = ".$result."\n";
  908. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  909. $result = (string) dol_eval("sprintf(\"%s%s\", \"ex\", \"ec\")('echo abc')", 1, 0);
  910. print "result12 = ".$result."\n";
  911. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  912. $result=dol_eval("90402.38+267678+0", 1, 1, 1);
  913. print "result13 = ".$result."\n";
  914. $this->assertEquals('358080.38', $result);
  915. global $leftmenu; // Used into strings to eval
  916. $conf->global->MAIN_FEATURES_LEVEL = 1;
  917. $leftmenu = 'AAA';
  918. $result=dol_eval('$conf->currency && preg_match(\'/^(AAA|BBB)/\',$leftmenu)', 1, 1, '1');
  919. print "result = ".$result."\n";
  920. $this->assertTrue($result);
  921. // Same with a value that does not match
  922. $leftmenu = 'XXX';
  923. $result=dol_eval('$conf->currency && preg_match(\'/^(AAA|BBB)/\',$leftmenu)', 1, 1, '1');
  924. print "result14 = ".$result."\n";
  925. $this->assertFalse($result);
  926. $leftmenu = 'AAA';
  927. $result=dol_eval('$conf->currency && isStringVarMatching(\'leftmenu\', \'(AAA|BBB)\')', 1, 1, '1');
  928. print "result15 = ".$result."\n";
  929. $this->assertTrue($result);
  930. $leftmenu = 'XXX';
  931. $result=dol_eval('$conf->currency && isStringVarMatching(\'leftmenu\', \'(AAA|BBB)\')', 1, 1, '1');
  932. print "result16 = ".$result."\n";
  933. $this->assertFalse($result);
  934. $string = '(isModEnabled("user") || isModEnabled("resource")) && getDolGlobalInt("MAIN_FEATURES_LEVEL") >= 0 && preg_match(\'/^(admintools|all|XXX)/\', $leftmenu)';
  935. $result=dol_eval($string, 1, 1, '1');
  936. print "result17 = ".$result."\n";
  937. $this->assertTrue($result);
  938. $result=dol_eval('1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL', 1, 0); // Should return false and not a 'Bad string syntax to evaluate ...'
  939. print "result18 = ".$result."\n";
  940. $this->assertFalse($result);
  941. $a='ab';
  942. $result = (string) dol_eval("(\$a.'s')", 1, 0);
  943. print "result19 = ".$result."\n";
  944. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  945. $leftmenu='abs';
  946. $result = (string) dol_eval('$leftmenu(-5)', 1, 0);
  947. print "result20 = ".$result."\n";
  948. $this->assertStringContainsString('Bad string syntax to evaluate', $result);
  949. }
  950. /**
  951. * testDolPrintHTML.
  952. * This method include calls to dol_htmlwithnojs()
  953. *
  954. * @return int
  955. */
  956. public function testDolPrintHTML()
  957. {
  958. global $conf;
  959. // Set options for cleaning data
  960. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 0; // disabled, does not work on HTML5 and some libxml versions
  961. // Enabled option MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY if possible
  962. if (extension_loaded('tidy') && class_exists("tidy")) {
  963. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY = 1;
  964. }
  965. $conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES = 0; // disabled, does not work on HTML5 and some libxml versions
  966. // For a string that is already HTML (contains HTML tags) with special tags but badly formated
  967. $stringtotest = "&quot;&gt;";
  968. $stringfixed = "&quot;&gt;";
  969. //$result = dol_htmlentitiesbr($stringtotest);
  970. //$result = dol_string_onlythesehtmltags(dol_htmlentitiesbr($stringtotest), 1, 1, 1, 0);
  971. //$result = dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($stringtotest), 1, 1, 1, 0));
  972. //$result = dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($stringtotest), 1, 1, 1, 0)), 1, 1, 'common', 0, 1);
  973. $result = dolPrintHTML($stringtotest);
  974. print __METHOD__." result=".$result."\n";
  975. $this->assertEquals($stringfixed, $result, 'Error'); // Expected '' because should failed because login 'auto' does not exists
  976. // For a string that is already HTML (contains HTML tags) with special tags but badly formated
  977. $stringtotest = "testA\n<h1>hhhh</h1><z>ddd</z><header>aaa</header><footer>bbb</footer>";
  978. if (getDolGlobalString("MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY")) {
  979. $stringfixed = "testA\n<h1>hhhh</h1>\nddd\n<header>aaa</header>\n<footer>bbb</footer>\n";
  980. } else {
  981. $stringfixed = "testA\n<h1>hhhh</h1>ddd<header>aaa</header><footer>bbb</footer>";
  982. }
  983. //$result = dol_htmlentitiesbr($stringtotest);
  984. //$result = dol_string_onlythesehtmltags(dol_htmlentitiesbr($stringtotest), 1, 1, 1, 0);
  985. //$result = dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($stringtotest), 1, 1, 1, 0));
  986. //$result = dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($stringtotest), 1, 1, 1, 0)), 1, 1, 'common', 0, 1);
  987. $result = dolPrintHTML($stringtotest);
  988. print __METHOD__." result=".$result."\n";
  989. $this->assertEquals($stringfixed, $result, 'Error');
  990. // For a string that is already HTML (contains HTML tags) but badly formated
  991. $stringtotest = "testB\n<h1>hhh</h1>\n<td>td alone</td><h1>iii</h1>";
  992. if (getDolGlobalString("MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY")) {
  993. $stringfixed = "testB\n<h1>hhh</h1>\n<h1>iii</h1>\n<table>\n<tr>\n<td>td alone</td>\n</tr>\n</table>\n";
  994. } else {
  995. $stringfixed = "testB\n<h1>hhh</h1>\n<td>td alone</td><h1>iii</h1>";
  996. }
  997. $result = dolPrintHTML($stringtotest);
  998. print __METHOD__." result=".$result."\n";
  999. $this->assertEquals($stringfixed, $result, 'Error');
  1000. // For a string with no HTML tags
  1001. $stringtotest = "testC\ntest";
  1002. $stringfixed = "testC<br>\ntest";
  1003. $result = dolPrintHTML($stringtotest);
  1004. print __METHOD__." result=".$result."\n";
  1005. $this->assertEquals($stringfixed, $result, 'Error');
  1006. return 0;
  1007. }
  1008. /**
  1009. * testCheckLoginPassEntity
  1010. *
  1011. * @return void
  1012. */
  1013. public function testCheckLoginPassEntity()
  1014. {
  1015. $login=checkLoginPassEntity('loginbidon', 'passwordbidon', 1, array('dolibarr'));
  1016. print __METHOD__." login=".$login."\n";
  1017. $this->assertEquals($login, '');
  1018. $login=checkLoginPassEntity('admin', 'passwordbidon', 1, array('dolibarr'));
  1019. print __METHOD__." login=".$login."\n";
  1020. $this->assertEquals($login, '');
  1021. $login=checkLoginPassEntity('admin', 'admin', 1, array('dolibarr')); // Should works because admin/admin exists
  1022. print __METHOD__." login=".$login."\n";
  1023. $this->assertEquals($login, 'admin', 'The test to check if pass of user "admin" is "admin" has failed');
  1024. $login=checkLoginPassEntity('admin', 'admin', 1, array('http','dolibarr')); // Should work because of second authentication method
  1025. print __METHOD__." login=".$login."\n";
  1026. $this->assertEquals($login, 'admin');
  1027. $login=checkLoginPassEntity('admin', 'admin', 1, array('forceuser'));
  1028. print __METHOD__." login=".$login."\n";
  1029. $this->assertEquals('', $login, 'Error'); // Expected '' because should failed because login 'auto' does not exists
  1030. }
  1031. }