SecurityTest.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. <?php
  2. /* Copyright (C) 2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. * or see https://www.gnu.org/
  17. */
  18. /**
  19. * \file test/phpunit/SecurityTest.php
  20. * \ingroup test
  21. * \brief PHPUnit test
  22. * \remarks To run this script as CLI: phpunit filename.php
  23. */
  24. global $conf,$user,$langs,$db;
  25. //define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver
  26. //require_once 'PHPUnit/Autoload.php';
  27. if (! defined('NOREQUIRESOC')) {
  28. define('NOREQUIRESOC', '1');
  29. }
  30. if (! defined('NOCSRFCHECK')) {
  31. define('NOCSRFCHECK', '1');
  32. }
  33. if (! defined('NOTOKENRENEWAL')) {
  34. define('NOTOKENRENEWAL', '1');
  35. }
  36. if (! defined('NOREQUIREMENU')) {
  37. define('NOREQUIREMENU', '1'); // If there is no menu to show
  38. }
  39. if (! defined('NOREQUIREHTML')) {
  40. define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
  41. }
  42. if (! defined('NOREQUIREAJAX')) {
  43. define('NOREQUIREAJAX', '1');
  44. }
  45. if (! defined("NOLOGIN")) {
  46. define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
  47. }
  48. if (! defined("NOSESSION")) {
  49. define("NOSESSION", '1');
  50. }
  51. require_once dirname(__FILE__).'/../../htdocs/main.inc.php';
  52. require_once dirname(__FILE__).'/../../htdocs/core/lib/security.lib.php';
  53. require_once dirname(__FILE__).'/../../htdocs/core/lib/security2.lib.php';
  54. if (empty($user->id)) {
  55. print "Load permissions for admin user nb 1\n";
  56. $user->fetch(1);
  57. $user->getrights();
  58. }
  59. $conf->global->MAIN_DISABLE_ALL_MAILS=1;
  60. /**
  61. * Class for PHPUnit tests
  62. *
  63. * @backupGlobals disabled
  64. * @backupStaticAttributes enabled
  65. * @remarks backupGlobals must be disabled to have db,conf,user and lang not erased.
  66. */
  67. class SecurityTest extends PHPUnit\Framework\TestCase
  68. {
  69. protected $savconf;
  70. protected $savuser;
  71. protected $savlangs;
  72. protected $savdb;
  73. /**
  74. * Constructor
  75. * We save global variables into local variables
  76. *
  77. * @return SecurityTest
  78. */
  79. public function __construct()
  80. {
  81. parent::__construct();
  82. //$this->sharedFixture
  83. global $conf,$user,$langs,$db;
  84. $this->savconf=$conf;
  85. $this->savuser=$user;
  86. $this->savlangs=$langs;
  87. $this->savdb=$db;
  88. print __METHOD__." db->type=".$db->type." user->id=".$user->id;
  89. //print " - db ".$db->db;
  90. print "\n";
  91. }
  92. /**
  93. * setUpBeforeClass
  94. *
  95. * @return void
  96. */
  97. public static function setUpBeforeClass()
  98. {
  99. global $conf,$user,$langs,$db;
  100. $db->begin(); // This is to have all actions inside a transaction even if test launched without suite.
  101. print __METHOD__."\n";
  102. }
  103. /**
  104. * tearDownAfterClass
  105. *
  106. * @return void
  107. */
  108. public static function tearDownAfterClass()
  109. {
  110. global $conf,$user,$langs,$db;
  111. $db->rollback();
  112. print __METHOD__."\n";
  113. }
  114. /**
  115. * Init phpunit tests
  116. *
  117. * @return void
  118. */
  119. protected function setUp()
  120. {
  121. global $conf,$user,$langs,$db;
  122. $conf=$this->savconf;
  123. $user=$this->savuser;
  124. $langs=$this->savlangs;
  125. $db=$this->savdb;
  126. print __METHOD__."\n";
  127. }
  128. /**
  129. * End phpunit tests
  130. *
  131. * @return void
  132. */
  133. protected function tearDown()
  134. {
  135. print __METHOD__."\n";
  136. }
  137. /**
  138. * testSetLang
  139. *
  140. * @return string
  141. */
  142. public function testSetLang()
  143. {
  144. global $conf;
  145. $conf=$this->savconf;
  146. $tmplangs = new Translate('', $conf);
  147. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = "' malicious text with quote";
  148. $tmplangs->setDefaultLang('auto');
  149. print __METHOD__.' $tmplangs->defaultlang='.$tmplangs->defaultlang."\n";
  150. $this->assertEquals($tmplangs->defaultlang, 'malicioustextwithquote_MALICIOUSTEXTWITHQUOTE');
  151. }
  152. /**
  153. * testSqlAndScriptInjectWithPHPUnit
  154. *
  155. * @return void
  156. */
  157. public function testSqlAndScriptInjectWithPHPUnit()
  158. {
  159. // Run tests
  160. // More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  161. // Should be OK
  162. $expectedresult=0;
  163. /*
  164. $test = '';
  165. $result=testSqlAndScriptInject($test, 0);
  166. $this->assertGreaterThanOrEqual(0, $result, 'Error on testSqlAndScriptInject kkk');
  167. */
  168. $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php';
  169. $result=testSqlAndScriptInject($_SERVER["PHP_SELF"], 2);
  170. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for PHP_SELF that should be ok');
  171. $test = 'This is a < inside string with < and > also and tag like <a> before the >';
  172. $result=testSqlAndScriptInject($test, 0);
  173. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject expected 0b');
  174. $test = 'This is the union of all for the selection of the best';
  175. $result=testSqlAndScriptInject($test, 0);
  176. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject expected 0c');
  177. // Should detect attack
  178. $expectedresult=1;
  179. $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php/<svg>';
  180. $result=testSqlAndScriptInject($_SERVER["PHP_SELF"], 2);
  181. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject for PHP_SELF that should detect XSS');
  182. $test = 'select @@version';
  183. $result=testSqlAndScriptInject($test, 0);
  184. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL1a. Should find an attack on POST param and did not.');
  185. $test = 'select @@version';
  186. $result=testSqlAndScriptInject($test, 1);
  187. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL1b. Should find an attack on GET param and did not.');
  188. $test = '... union ... selection ';
  189. $result=testSqlAndScriptInject($test, 1);
  190. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for SQL2. Should find an attack on GET param and did not.');
  191. $test = 'j&#x61;vascript:';
  192. $result=testSqlAndScriptInject($test, 0);
  193. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for javascript1. Should find an attack and did not.');
  194. $test = 'j&#x61vascript:';
  195. $result=testSqlAndScriptInject($test, 0);
  196. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for javascript2. Should find an attack and did not.');
  197. $test = 'javascript&colon&#x3B;alert(1)';
  198. $result=testSqlAndScriptInject($test, 0);
  199. $this->assertEquals($expectedresult, $result, 'Error on testSqlAndScriptInject for javascript2');
  200. $test="<img src='1.jpg' onerror =javascript:alert('XSS')>";
  201. $result=testSqlAndScriptInject($test, 0);
  202. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa1');
  203. $test="<img src='1.jpg' onerror =javascript:alert('XSS')>";
  204. $result=testSqlAndScriptInject($test, 2);
  205. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa2');
  206. $test='<IMG SRC=# onmouseover="alert(1)">';
  207. $result=testSqlAndScriptInject($test, 0);
  208. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa3');
  209. $test='<IMG SRC onmouseover="alert(1)">';
  210. $result=testSqlAndScriptInject($test, 0);
  211. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa4');
  212. $test='<IMG onmouseover="alert(1)">';
  213. $result=testSqlAndScriptInject($test, 0);
  214. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa5');
  215. $test='<IMG SRC=/ onerror="alert(1)">';
  216. $result=testSqlAndScriptInject($test, 0);
  217. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa6');
  218. $test='<IMG SRC=" &#14; javascript:alert(1);">';
  219. $result=testSqlAndScriptInject($test, 0);
  220. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject aaa7');
  221. $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;>';
  222. $result=testSqlAndScriptInject($test, 0);
  223. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject bbb');
  224. $test='<SCRIPT SRC=http://xss.rocks/xss.js></SCRIPT>';
  225. $result=testSqlAndScriptInject($test, 0);
  226. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject ccc');
  227. $test='<IMG SRC="javascript:alert(\'XSS\');">';
  228. $result=testSqlAndScriptInject($test, 1);
  229. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject ddd');
  230. $test='<IMG """><SCRIPT>alert("XSS")</SCRIPT>">';
  231. $result=testSqlAndScriptInject($test, 0);
  232. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject eee');
  233. $test='<!-- Google analytics -->
  234. <script>
  235. (function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){
  236. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  237. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  238. })(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\');
  239. ga(\'create\',\'UA-99999999-9\', \'auto\');
  240. ga(\'send\', \'pageview\');
  241. </script>';
  242. $result=testSqlAndScriptInject($test, 0);
  243. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject eee');
  244. $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.
  245. $test="<IMG SRC=\"jav&#x0D;ascript:alert('XSS');\">"; // Same
  246. $test='<SCRIPT/XSS SRC="http://xss.rocks/xss.js"></SCRIPT>';
  247. $result=testSqlAndScriptInject($test, 0);
  248. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject fff1');
  249. $test='<SCRIPT/SRC="http://xss.rocks/xss.js"></SCRIPT>';
  250. $result=testSqlAndScriptInject($test, 0);
  251. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject fff2');
  252. // This case seems to be filtered by browsers now.
  253. $test='<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert(1)>';
  254. //$result=testSqlAndScriptInject($test, 0);
  255. //$this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject ggg');
  256. $test='<iframe src=http://xss.rocks/scriptlet.html <';
  257. $result=testSqlAndScriptInject($test, 0);
  258. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject hhh');
  259. $test='Set.constructor`alert\x281\x29```';
  260. $result=testSqlAndScriptInject($test, 0);
  261. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject iii');
  262. $test="on<!-- ab\nc -->error=alert(1)";
  263. $result=testSqlAndScriptInject($test, 0);
  264. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject jjj');
  265. $test="<img src=x one<a>rror=alert(document.location)";
  266. $result=testSqlAndScriptInject($test, 0);
  267. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject kkk');
  268. $test="<a onpointerdown=alert(document.domain)>XSS</a>";
  269. $result=testSqlAndScriptInject($test, 0);
  270. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject lll');
  271. $test="Text with ' encoded with the numeric html entity converted into text entity &#39; (like when submited by CKEditor)";
  272. $result=testSqlAndScriptInject($test, 0); // result must be 0
  273. $this->assertEquals(0, $result, 'Error on testSqlAndScriptInject mmm');
  274. $test="/dolibarr/htdocs/index.php/".chr('246')."abc"; // Add the char %F6 into the variable
  275. $result=testSqlAndScriptInject($test, 2);
  276. //print "test=".$test." result=".$result."\n";
  277. $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on testSqlAndScriptInject with a non valid UTF8 char');
  278. }
  279. /**
  280. * testGETPOST
  281. *
  282. * @return string
  283. */
  284. public function testGETPOST()
  285. {
  286. global $conf,$user,$langs,$db;
  287. $conf=$this->savconf;
  288. $user=$this->savuser;
  289. $langs=$this->savlangs;
  290. $db=$this->savdb;
  291. // Force default mode
  292. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 0;
  293. $conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES = 0;
  294. $_COOKIE["id"]=111;
  295. $_GET["param1"]="222";
  296. $_POST["param1"]="333";
  297. $_GET["param2"]='a/b#e(pr)qq-rr\cc';
  298. $_GET["param3"]='"&#110;a/b#e(pr)qq-rr\cc'; // Same than param2 + " and &#110;
  299. $_GET["param4a"]='..&#47;../dir';
  300. $_GET["param4b"]='..&#92;..\dirwindows';
  301. $_GET["param5"]="a_1-b";
  302. $_POST["param6"]="&quot;&gt;<svg o&#110;load='console.log(&quot;123&quot;)'&gt;";
  303. $_POST["param6b"]='<<<../>../>../svg><<<../>../>../animate =alert(1)>abc';
  304. $_GET["param7"]='"c:\this is a path~1\aaa&#110; &#x&#x31;&#x31;&#x30;;" abc<bad>def</bad>';
  305. $_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
  306. $_POST['param8b']='<img src=x onerror=alert(document.location) t='; // this is html obfuscated by non closing tag
  307. $_POST['param8c']='< with space after is ok';
  308. $_POST['param8d']='<abc123 is html to clean';
  309. $_POST['param8e']='<123abc is not html to clean'; // other similar case: '<2021-12-12'
  310. $_POST['param8f']='abc<<svg <><<animate onbegin=alert(document.domain) a';
  311. $_POST["param9"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'objnotdefined\'';
  312. $_POST["param10"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'<abc>objnotdefined\'';
  313. $_POST["param11"]=' Name <email@email.com> ';
  314. $_POST["param12"]='<!DOCTYPE html><html>aaa</html>';
  315. $_POST["param13"]='&#110; &#x6E; &gt; &lt; &quot; <a href=\"j&#x61;vascript:alert(document.domain)\">XSS</a>';
  316. $_POST["param13b"]='&#110; &#x6E; &gt; &lt; &quot; <a href=\"j&#x61vascript:alert(document.domain)\">XSS</a>';
  317. $_POST["param14"]="Text with ' encoded with the numeric html entity converted into text entity &#39; (like when submited by CKEditor)";
  318. $_POST["param15"]="<img onerror<=alert(document.domain)> src=>0xbeefed";
  319. //$_POST["param13"]='javascript%26colon%26%23x3B%3Balert(1)';
  320. //$_POST["param14"]='javascripT&javascript#x3a alert(1)';
  321. $result=GETPOST('id', 'int'); // Must return nothing
  322. print __METHOD__." result=".$result."\n";
  323. $this->assertEquals($result, '');
  324. $result=GETPOST("param1", 'int');
  325. print __METHOD__." result=".$result."\n";
  326. $this->assertEquals($result, 222, 'Test on param1 with no 3rd param');
  327. $result=GETPOST("param1", 'int', 2);
  328. print __METHOD__." result=".$result."\n";
  329. $this->assertEquals($result, 333, 'Test on param1 with 3rd param = 2');
  330. // Test with alpha
  331. $result=GETPOST("param2", 'alpha');
  332. print __METHOD__." result=".$result."\n";
  333. $this->assertEquals($result, $_GET["param2"], 'Test on param2');
  334. $result=GETPOST("param3", 'alpha'); // Must return string sanitized from char "
  335. print __METHOD__." result=".$result."\n";
  336. $this->assertEquals($result, 'na/b#e(pr)qq-rr\cc', 'Test on param3');
  337. $result=GETPOST("param4a", 'alpha'); // Must return string sanitized from ../
  338. print __METHOD__." result=".$result."\n";
  339. $this->assertEquals($result, 'dir');
  340. $result=GETPOST("param4b", 'alpha'); // Must return string sanitized from ../
  341. print __METHOD__." result=".$result."\n";
  342. $this->assertEquals($result, 'dirwindows');
  343. // Test with aZ09
  344. $result=GETPOST("param1", 'aZ09');
  345. print __METHOD__." result=".$result."\n";
  346. $this->assertEquals($result, $_GET["param1"]);
  347. $result=GETPOST("param2", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  348. print __METHOD__." result=".$result."\n";
  349. $this->assertEquals($result, '');
  350. $result=GETPOST("param3", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  351. print __METHOD__." result=".$result."\n";
  352. $this->assertEquals($result, '');
  353. $result=GETPOST("param4a", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  354. print __METHOD__." result=".$result."\n";
  355. $this->assertEquals('', $result);
  356. $result=GETPOST("param4b", 'aZ09'); // Must return '' as string contains car not in aZ09 definition
  357. print __METHOD__." result=".$result."\n";
  358. $this->assertEquals('', $result);
  359. $result=GETPOST("param5", 'aZ09');
  360. print __METHOD__." result=".$result."\n";
  361. $this->assertEquals($_GET["param5"], $result);
  362. // Test with nohtml
  363. $result=GETPOST("param6", 'nohtml');
  364. print __METHOD__." result=".$result."\n";
  365. $this->assertEquals('">', $result);
  366. // Test with alpha = alphanohtml. We must convert the html entities like &#110; and disable all entities
  367. $result=GETPOST("param6", 'alphanohtml');
  368. print __METHOD__." result=".$result."\n";
  369. $this->assertEquals('>', $result);
  370. $result=GETPOST("param6b", 'alphanohtml');
  371. print __METHOD__." result=".$result."\n";
  372. $this->assertEquals('abc', $result);
  373. $result=GETPOST("param8a", 'alphanohtml');
  374. print __METHOD__." result=".$result."\n";
  375. $this->assertEquals("Hackersvg onload='console.log(123)'", $result);
  376. $result=GETPOST("param8b", 'alphanohtml');
  377. print __METHOD__." result=".$result."\n";
  378. $this->assertEquals('img src=x onerror=alert(document.location) t=', $result, 'Test a string with non closing html tag with alphanohtml');
  379. $result=GETPOST("param8c", 'alphanohtml');
  380. print __METHOD__." result=".$result."\n";
  381. $this->assertEquals($_POST['param8c'], $result, 'Test a string with non closing html tag with alphanohtml');
  382. $result=GETPOST("param8d", 'alphanohtml');
  383. print __METHOD__." result=".$result."\n";
  384. $this->assertEquals('abc123 is html to clean', $result, 'Test a string with non closing html tag with alphanohtml');
  385. $result=GETPOST("param8e", 'alphanohtml');
  386. print __METHOD__." result=".$result."\n";
  387. $this->assertEquals($_POST['param8e'], $result, 'Test a string with non closing html tag with alphanohtml');
  388. $result=GETPOST("param8f", 'alphanohtml');
  389. print __METHOD__." result=".$result."\n";
  390. $this->assertEquals('abcsvg animate onbegin=alert(document.domain) a', $result, 'Test a string with html tag open with several <');
  391. $result=GETPOST("param9", 'alphanohtml');
  392. print __METHOD__." result=".$result."\n";
  393. $this->assertEquals($_POST["param9"], $result);
  394. $result=GETPOST("param10", 'alphanohtml');
  395. print __METHOD__." result=".$result."\n";
  396. $this->assertEquals($_POST["param9"], $result, 'We should get param9 after processing param10');
  397. $result=GETPOST("param11", 'alphanohtml');
  398. print __METHOD__." result=".$result."\n";
  399. $this->assertEquals("Name", $result, 'Test an email string with alphanohtml');
  400. $result=GETPOST("param13", 'alphanohtml');
  401. print __METHOD__." result=".$result."\n";
  402. $this->assertEquals('n n > < XSS', $result, 'Test that html entities are decoded with alpha');
  403. // Test with alphawithlgt
  404. $result=GETPOST("param11", 'alphawithlgt');
  405. print __METHOD__." result=".$result."\n";
  406. $this->assertEquals(trim($_POST["param11"]), $result, 'Test an email string with alphawithlgt');
  407. // 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;)
  408. $result=GETPOST("param6", 'restricthtml');
  409. print __METHOD__." result param6=".$result."\n";
  410. $this->assertEquals('&quot;&gt;', $result);
  411. $result=GETPOST("param7", 'restricthtml');
  412. print __METHOD__." result param7 = ".$result."\n";
  413. $this->assertEquals('"c:\this is a path~1\aaan &#x;;;;" abcdef', $result);
  414. $result=GETPOST("param8e", 'restricthtml');
  415. print __METHOD__." result param8e = ".$result."\n";
  416. $this->assertEquals('', $result);
  417. $result=GETPOST("param12", 'restricthtml');
  418. print __METHOD__." result=".$result."\n";
  419. $this->assertEquals(trim($_POST["param12"]), $result, 'Test a string with DOCTYPE and restricthtml');
  420. $result=GETPOST("param13", 'restricthtml');
  421. print __METHOD__." result=".$result."\n";
  422. $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');
  423. $result=GETPOST("param13b", 'restricthtml');
  424. print __METHOD__." result=".$result."\n";
  425. $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');
  426. $result=GETPOST("param14", 'restricthtml');
  427. print __METHOD__." result=".$result."\n";
  428. $this->assertEquals("Text with ' encoded with the numeric html entity converted into text entity &#39; (like when submited by CKEditor)", $result, 'Test 14');
  429. $result=GETPOST("param15", 'restricthtml'); // <img onerror<=alert(document.domain)> src=>0xbeefed
  430. print __METHOD__." result=".$result."\n";
  431. $this->assertEquals("<img onerror=alert(document.domain) src=>0xbeefed", $result, 'Test 15'); // The GETPOST return a harmull string
  432. // Test with restricthtml + MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES to test disabling of bad atrributes
  433. $conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML = 1;
  434. $result=GETPOST("param15", 'restricthtml');
  435. print __METHOD__." result=".$result."\n";
  436. $this->assertEquals('InvalidHTMLString', $result, 'Test 15b');
  437. unset($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML);
  438. // Test with restricthtml + MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES to test disabling of bad atrributes
  439. $conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES = 1;
  440. $result=GETPOST("param15", 'restricthtml');
  441. print __METHOD__." result=".$result."\n";
  442. $this->assertEquals('<img src="">0xbeefed', $result, 'Test 15b');
  443. unset($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES);
  444. // Special test for GETPOST of backtopage, backtolist or backtourl parameter
  445. $_POST["backtopage"]='//www.google.com';
  446. $result=GETPOST("backtopage");
  447. print __METHOD__." result=".$result."\n";
  448. $this->assertEquals('www.google.com', $result, 'Test for backtopage param');
  449. $_POST["backtopage"]='https:https://www.google.com';
  450. $result=GETPOST("backtopage");
  451. print __METHOD__." result=".$result."\n";
  452. $this->assertEquals('www.google.com', $result, 'Test for backtopage param');
  453. $_POST["backtolist"]='::HTTPS://www.google.com';
  454. $result=GETPOST("backtolist");
  455. print __METHOD__." result=".$result."\n";
  456. $this->assertEquals('www.google.com', $result, 'Test for backtopage param');
  457. $_POST["backtopage"]='http:www.google.com';
  458. $result=GETPOST("backtopage");
  459. print __METHOD__." result=".$result."\n";
  460. $this->assertEquals('httpwww.google.com', $result, 'Test for backtopage param');
  461. $_POST["backtopage"]='/mydir/mypage.php?aa=a%10a';
  462. $result=GETPOST("backtopage");
  463. print __METHOD__." result=".$result."\n";
  464. $this->assertEquals('/mydir/mypage.php?aa=a%10a', $result, 'Test for backtopage param');
  465. $_POST["backtopage"]='javascripT&javascript#javascriptxjavascript3a alert(1)';
  466. $result=GETPOST("backtopage");
  467. print __METHOD__." result=".$result."\n";
  468. $this->assertEquals('x3aalert(1)', $result, 'Test for backtopage param');
  469. return $result;
  470. }
  471. /**
  472. * testEncodeDecode
  473. *
  474. * @return number
  475. */
  476. public function testEncodeDecode()
  477. {
  478. $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.";
  479. $encodedstring=dol_encode($stringtotest);
  480. $decodedstring=dol_decode($encodedstring);
  481. print __METHOD__." encodedstring=".$encodedstring." ".base64_encode($stringtotest)."\n";
  482. $this->assertEquals($stringtotest, $decodedstring, 'Use dol_encode/decode with no parameter');
  483. $encodedstring=dol_encode($stringtotest, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
  484. $decodedstring=dol_decode($encodedstring, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
  485. print __METHOD__." encodedstring=".$encodedstring." ".base64_encode($stringtotest)."\n";
  486. $this->assertEquals($stringtotest, $decodedstring, 'Use dol_encode/decode with a key parameter');
  487. return 0;
  488. }
  489. /**
  490. * testDolStringOnlyTheseHtmlTags
  491. *
  492. * @return number
  493. */
  494. public function testDolHTMLEntityDecode()
  495. {
  496. $stringtotest = 'a &colon; b &quot; c &#039; d &apos; e &eacute;';
  497. $decodedstring = dol_html_entity_decode($stringtotest, ENT_QUOTES);
  498. $this->assertEquals('a &colon; b " c \' d &apos; e é', $decodedstring, 'Function did not sanitize correclty');
  499. $stringtotest = 'a &colon; b &quot; c &#039; d &apos; e &eacute;';
  500. $decodedstring = dol_html_entity_decode($stringtotest, ENT_QUOTES|ENT_HTML5);
  501. $this->assertEquals('a : b " c \' d \' e é', $decodedstring, 'Function did not sanitize correclty');
  502. return 0;
  503. }
  504. /**
  505. * testDolStringOnlyTheseHtmlTags
  506. *
  507. * @return number
  508. */
  509. public function testDolStringOnlyTheseHtmlTags()
  510. {
  511. $stringtotest = '<a href="javascript:aaa">bbbڴ';
  512. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1);
  513. $this->assertEquals('<a href="aaa">bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 1');
  514. $stringtotest = '<a href="java'.chr(0).'script:aaa">bbbڴ';
  515. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1);
  516. $this->assertEquals('<a href="aaa">bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 2');
  517. $stringtotest = '<a href="javascript&colon;aaa">bbbڴ';
  518. $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1);
  519. $this->assertEquals('<a href="aaa">bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 3');
  520. return 0;
  521. }
  522. /**
  523. * testDolStringOnlyTheseHtmlAttributes
  524. *
  525. * @return number
  526. */
  527. public function testDolStringOnlyTheseHtmlAttributes()
  528. {
  529. $stringtotest = 'eée';
  530. $decodedstring = dol_string_onlythesehtmlattributes($stringtotest);
  531. $this->assertEquals('e&eacute;e', $decodedstring, 'Function did not sanitize correclty with test 1');
  532. $stringtotest = '<div onload="ee"><a href="123"><span class="abc">abc</span></a></div>';
  533. $decodedstring = dol_string_onlythesehtmlattributes($stringtotest);
  534. $decodedstring = preg_replace("/\n$/", "", $decodedstring);
  535. $this->assertEquals('<div><a href="123"><span class="abc">abc</span></a></div>', $decodedstring, 'Function did not sanitize correclty with test 2');
  536. return 0;
  537. }
  538. /**
  539. * testGetRandomPassword
  540. *
  541. * @return number
  542. */
  543. public function testGetRandomPassword()
  544. {
  545. global $conf;
  546. $genpass1=getRandomPassword(true); // Should be a string return by dol_hash (if no option set, will be md5)
  547. print __METHOD__." genpass1=".$genpass1."\n";
  548. $this->assertEquals(strlen($genpass1), 32);
  549. $genpass1=getRandomPassword(true, array('I')); // Should be a string return by dol_hash (if no option set, will be md5)
  550. print __METHOD__." genpass1=".$genpass1."\n";
  551. $this->assertEquals(strlen($genpass1), 32);
  552. $conf->global->USER_PASSWORD_GENERATED='None';
  553. $genpass2=getRandomPassword(false); // Should return an empty string
  554. print __METHOD__." genpass2=".$genpass2."\n";
  555. $this->assertEquals($genpass2, '');
  556. $conf->global->USER_PASSWORD_GENERATED='Standard';
  557. $genpass3=getRandomPassword(false); // Should return a password of 12 chars
  558. print __METHOD__." genpass3=".$genpass3."\n";
  559. $this->assertEquals(strlen($genpass3), 12);
  560. return 0;
  561. }
  562. /**
  563. * testRestrictedArea
  564. *
  565. * @return void
  566. */
  567. public function testRestrictedArea()
  568. {
  569. global $conf,$user,$langs,$db;
  570. $conf=$this->savconf;
  571. $user=$this->savuser;
  572. $langs=$this->savlangs;
  573. $db=$this->savdb;
  574. //$dummyuser=new User($db);
  575. //$result=restrictedArea($dummyuser,'societe');
  576. $result=restrictedArea($user, 'societe');
  577. $this->assertEquals(1, $result);
  578. }
  579. /**
  580. * testGetRandomPassword
  581. *
  582. * @return number
  583. */
  584. public function testGetURLContent()
  585. {
  586. global $conf;
  587. include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  588. $url = 'ftp://mydomain.com';
  589. $tmp = getURLContent($url);
  590. print __METHOD__." url=".$url."\n";
  591. $this->assertGreaterThan(0, strpos($tmp['curl_error_msg'], 'not supported')); // Test error if return does not contains 'not supported'
  592. $url = 'https://www.dolibarr.fr'; // This is a redirect 301 page
  593. $tmp = getURLContent($url, 'GET', '', 0); // We do NOT follow
  594. print __METHOD__." url=".$url."\n";
  595. $this->assertEquals(301, $tmp['http_code'], 'Should GET url 301 without following -> 301');
  596. $url = 'https://www.dolibarr.fr'; // This is a redirect 301 page
  597. $tmp = getURLContent($url); // We DO follow a page with return 300 so result should be 200
  598. print __METHOD__." url=".$url."\n";
  599. $this->assertEquals(200, $tmp['http_code'], 'Should GET url 301 with following -> 200 but we get '.$tmp['http_code']);
  600. $url = 'http://localhost';
  601. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  602. print __METHOD__." url=".$url."\n";
  603. $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
  604. $url = 'http://127.0.0.1';
  605. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  606. print __METHOD__." url=".$url."\n";
  607. $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
  608. $url = 'http://127.0.2.1';
  609. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  610. print __METHOD__." url=".$url."\n";
  611. $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
  612. $url = 'https://169.254.0.1';
  613. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  614. print __METHOD__." url=".$url."\n";
  615. $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
  616. $url = 'http://[::1]';
  617. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  618. print __METHOD__." url=".$url."\n";
  619. $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
  620. /*$url = 'localtest.me';
  621. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL
  622. print __METHOD__." url=".$url."\n";
  623. $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
  624. */
  625. $url = 'http://192.0.0.192';
  626. $tmp = getURLContent($url, 'GET', '', 0, array(), array('http', 'https'), 0); // Only external URL but on an IP in blacklist
  627. print __METHOD__." url=".$url." tmp['http_code'] = ".$tmp['http_code']."\n";
  628. $this->assertEquals(400, $tmp['http_code'], 'Access should be refused and was not'); // Test we receive an error because ip is in blacklist
  629. return 0;
  630. }
  631. /**
  632. * testDolSanitizeUrl
  633. *
  634. * @return void
  635. */
  636. public function testDolSanitizeUrl()
  637. {
  638. global $conf,$user,$langs,$db;
  639. $conf=$this->savconf;
  640. $user=$this->savuser;
  641. $langs=$this->savlangs;
  642. $db=$this->savdb;
  643. $test = 'javascripT&javascript#x3a alert(1)';
  644. $result=dol_sanitizeUrl($test);
  645. $this->assertEquals('x3a alert(1)', $result, 'Test on dol_sanitizeUrl A');
  646. $test = 'javajavascriptscript&cjavascriptolon;alert(1)';
  647. $result=dol_sanitizeUrl($test);
  648. $this->assertEquals('alert(1)', $result, 'Test on dol_sanitizeUrl B');
  649. $test = '/javas:cript/google.com';
  650. $result=dol_sanitizeUrl($test);
  651. $this->assertEquals('google.com', $result, 'Test on dol_sanitizeUrl C');
  652. }
  653. /**
  654. * testDolSanitizeFileName
  655. *
  656. * @return void
  657. */
  658. public function testDolSanitizeFileName()
  659. {
  660. global $conf,$user,$langs,$db;
  661. $conf=$this->savconf;
  662. $user=$this->savuser;
  663. $langs=$this->savlangs;
  664. $db=$this->savdb;
  665. //$dummyuser=new User($db);
  666. //$result=restrictedArea($dummyuser,'societe');
  667. $result=dol_sanitizeFileName('bad file | evilaction');
  668. $this->assertEquals('bad file _ evilaction', $result);
  669. $result=dol_sanitizeFileName('bad file -evilparam --evilparam ---evilparam ----evilparam');
  670. $this->assertEquals('bad file _evilparam _evilparam _evilparam _evilparam', $result);
  671. }
  672. /**
  673. * testDolEval
  674. *
  675. * @return void
  676. */
  677. public function testDolEval()
  678. {
  679. global $conf,$user,$langs,$db;
  680. $conf=$this->savconf;
  681. $user=$this->savuser;
  682. $langs=$this->savlangs;
  683. $db=$this->savdb;
  684. $result=dol_eval('1==1', 1, 0);
  685. print "result = ".$result."\n";
  686. $this->assertTrue($result);
  687. $result=dol_eval('1==2', 1, 0);
  688. print "result = ".$result."\n";
  689. $this->assertFalse($result);
  690. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  691. include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  692. $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"';
  693. $result=dol_eval($s, 1, 1, '2');
  694. print "result = ".$result."\n";
  695. $this->assertEquals('Parent project not found', $result);
  696. $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\'';
  697. $result=dol_eval($s, 1, 1, '2');
  698. print "result = ".$result."\n";
  699. $this->assertEquals('Parent project not found', $result);
  700. $result=dol_eval('$a=function() { }; $a;', 1, 1, '');
  701. print "result = ".$result."\n";
  702. $this->assertContains('Bad string syntax to evaluate', $result);
  703. $result=dol_eval('$a=exec("ls");', 1, 1);
  704. print "result = ".$result."\n";
  705. $this->assertContains('Bad string syntax to evaluate', $result);
  706. $result=dol_eval('$a=exec ("ls")', 1, 1);
  707. print "result = ".$result."\n";
  708. $this->assertContains('Bad string syntax to evaluate', $result);
  709. $result=dol_eval('$a="test"; $$a;', 1, 0);
  710. print "result = ".$result."\n";
  711. $this->assertContains('Bad string syntax to evaluate', $result);
  712. $result=dol_eval('`ls`', 1, 0);
  713. print "result = ".$result."\n";
  714. $this->assertContains('Bad string syntax to evaluate', $result);
  715. $result=dol_eval("('ex'.'ec')('echo abc')", 1, 0);
  716. print "result = ".$result."\n";
  717. $this->assertContains('Bad string syntax to evaluate', $result);
  718. $result=dol_eval("sprintf(\"%s%s\", \"ex\", \"ec\")('echo abc')", 1, 0);
  719. print "result = ".$result."\n";
  720. $this->assertContains('Bad string syntax to evaluate', $result);
  721. $result=dol_eval("90402.38+267678+0", 1, 1, 1);
  722. print "result = ".$result."\n";
  723. $this->assertEquals('358080.38', $result);
  724. global $leftmenu; // Used into strings to eval
  725. $leftmenu = 'AAA';
  726. $result=dol_eval('$conf->currency && preg_match(\'/^(AAA|BBB)/\',$leftmenu)', 1, 1, '1');
  727. print "result = ".$result."\n";
  728. $this->assertTrue($result);
  729. // Same with syntax error
  730. $leftmenu = 'XXX';
  731. $result=dol_eval('$conf->currency && preg_match(\'/^(AAA|BBB)/\',$leftmenu)', 1, 1, '1');
  732. print "result = ".$result."\n";
  733. $this->assertFalse($result);
  734. // Case with param onlysimplestring = 1
  735. $result=dol_eval('1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL', 1, 0); // Should return false and not a 'Bad string syntax to evaluate ...'
  736. print "result = ".$result."\n";
  737. $this->assertFalse($result);
  738. $result=dol_eval("(\$a.'aa')", 1, 0);
  739. print "result = ".$result."\n";
  740. $this->assertContains('Bad string syntax to evaluate', $result);
  741. }
  742. /**
  743. * testCheckLoginPassEntity
  744. *
  745. * @return void
  746. */
  747. public function testCheckLoginPassEntity()
  748. {
  749. $login=checkLoginPassEntity('loginbidon', 'passwordbidon', 1, array('dolibarr'));
  750. print __METHOD__." login=".$login."\n";
  751. $this->assertEquals($login, '');
  752. $login=checkLoginPassEntity('admin', 'passwordbidon', 1, array('dolibarr'));
  753. print __METHOD__." login=".$login."\n";
  754. $this->assertEquals($login, '');
  755. $login=checkLoginPassEntity('admin', 'admin', 1, array('dolibarr')); // Should works because admin/admin exists
  756. print __METHOD__." login=".$login."\n";
  757. $this->assertEquals($login, 'admin', 'The test to check if pass of user "admin" is "admin" has failed');
  758. $login=checkLoginPassEntity('admin', 'admin', 1, array('http','dolibarr')); // Should work because of second authentication method
  759. print __METHOD__." login=".$login."\n";
  760. $this->assertEquals($login, 'admin');
  761. $login=checkLoginPassEntity('admin', 'admin', 1, array('forceuser'));
  762. print __METHOD__." login=".$login."\n";
  763. $this->assertEquals('', $login, 'Error'); // Expected '' because should failed because login 'auto' does not exists
  764. }
  765. }