SecurityComponentTest.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. <?php
  2. /**
  3. * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
  12. * @since CakePHP(tm) v 1.2.0.5435
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\Component\SecurityComponent;
  17. use Cake\Controller\Controller;
  18. use Cake\Core\Configure;
  19. use Cake\Event\Event;
  20. use Cake\Network\Request;
  21. use Cake\TestSuite\TestCase;
  22. use Cake\Utility\Security;
  23. /**
  24. * TestSecurityComponent
  25. *
  26. */
  27. class TestSecurityComponent extends SecurityComponent {
  28. /**
  29. * validatePost method
  30. *
  31. * @param Controller $controller
  32. * @return boolean
  33. */
  34. public function validatePost(Controller $controller) {
  35. return $this->_validatePost($controller);
  36. }
  37. }
  38. /**
  39. * SecurityTestController
  40. *
  41. */
  42. class SecurityTestController extends Controller {
  43. /**
  44. * components property
  45. *
  46. * @var array
  47. */
  48. public $components = array(
  49. 'Session',
  50. 'TestSecurity' => array('className' => 'Cake\Test\TestCase\Controller\Component\TestSecurityComponent')
  51. );
  52. /**
  53. * failed property
  54. *
  55. * @var boolean false
  56. */
  57. public $failed = false;
  58. /**
  59. * Used for keeping track of headers in test
  60. *
  61. * @var array
  62. */
  63. public $testHeaders = array();
  64. /**
  65. * fail method
  66. *
  67. * @return void
  68. */
  69. public function fail() {
  70. $this->failed = true;
  71. }
  72. /**
  73. * redirect method
  74. *
  75. * @param string|array $url
  76. * @param mixed $code
  77. * @param mixed $exit
  78. * @return void
  79. */
  80. public function redirect($url, $status = null, $exit = true) {
  81. return $status;
  82. }
  83. /**
  84. * Convenience method for header()
  85. *
  86. * @param string $status
  87. * @return void
  88. */
  89. public function header($status) {
  90. $this->testHeaders[] = $status;
  91. }
  92. }
  93. /**
  94. * SecurityComponentTest class
  95. *
  96. */
  97. class SecurityComponentTest extends TestCase {
  98. /**
  99. * Controller property
  100. *
  101. * @var SecurityTestController
  102. */
  103. public $Controller;
  104. /**
  105. * oldSalt property
  106. *
  107. * @var string
  108. */
  109. public $oldSalt;
  110. /**
  111. * setUp method
  112. *
  113. * @return void
  114. */
  115. public function setUp() {
  116. parent::setUp();
  117. $request = new Request('posts/index');
  118. $request->addParams(array('controller' => 'posts', 'action' => 'index'));
  119. $this->Controller = new SecurityTestController($request);
  120. $this->Controller->constructClasses();
  121. $this->Controller->Security = $this->Controller->TestSecurity;
  122. $this->Controller->Security->blackHoleCallback = 'fail';
  123. $this->Security = $this->Controller->Security;
  124. $this->Security->csrfCheck = false;
  125. Configure::write('Session', [
  126. 'defaults' => 'php'
  127. ]);
  128. Configure::write('Security.salt', 'foo!');
  129. }
  130. /**
  131. * Tear-down method. Resets environment state.
  132. *
  133. * @return void
  134. */
  135. public function tearDown() {
  136. parent::tearDown();
  137. $this->Controller->Session->delete('_Token');
  138. unset($this->Controller->Security);
  139. unset($this->Controller->Component);
  140. unset($this->Controller);
  141. }
  142. /**
  143. * Test that requests are still blackholed when controller has incorrect
  144. * visibility keyword in the blackhole callback
  145. *
  146. * @expectedException Cake\Error\BadRequestException
  147. */
  148. public function testBlackholeWithBrokenCallback() {
  149. $request = new Request('posts/index');
  150. $request->addParams([
  151. 'controller' => 'posts',
  152. 'action' => 'index'
  153. ]);
  154. $Controller = new \TestApp\Controller\SomePagesController($request);
  155. $event = new Event('Controller.startup', $Controller, $this->Controller);
  156. $Security = new SecurityComponent($Controller->Components);
  157. $Security->blackHoleCallback = '_fail';
  158. $Security->startup($event);
  159. $Security->blackHole($Controller, 'csrf');
  160. }
  161. /**
  162. * Ensure that directly requesting the blackholeCallback as the controller
  163. * action results in an exception.
  164. *
  165. * @return void
  166. */
  167. public function testExceptionWhenActionIsBlackholeCallback() {
  168. $this->Controller->request->addParams(array(
  169. 'controller' => 'posts',
  170. 'action' => 'fail'
  171. ));
  172. $event = new Event('Controller.startup', $this->Controller);
  173. $this->assertFalse($this->Controller->failed);
  174. $this->Controller->Security->startup($event);
  175. $this->assertTrue($this->Controller->failed, 'Request was blackholed.');
  176. }
  177. /**
  178. * test that initialize can set properties.
  179. *
  180. * @return void
  181. */
  182. public function testConstructorSettingProperties() {
  183. $settings = array(
  184. 'requireSecure' => array('update_account'),
  185. 'validatePost' => false,
  186. );
  187. $Security = new SecurityComponent($this->Controller->Components, $settings);
  188. $this->assertEquals($Security->validatePost, $settings['validatePost']);
  189. }
  190. /**
  191. * testStartup method
  192. *
  193. * @return void
  194. */
  195. public function testStartup() {
  196. $event = new Event('Controller.startup', $this->Controller);
  197. $this->Controller->Security->startup($event);
  198. $result = $this->Controller->request->params['_Token']['key'];
  199. $this->assertNotNull($result);
  200. $this->assertTrue($this->Controller->Session->check('_Token'));
  201. }
  202. /**
  203. * testRequireSecureFail method
  204. *
  205. * @return void
  206. */
  207. public function testRequireSecureFail() {
  208. $_SERVER['HTTPS'] = 'off';
  209. $_SERVER['REQUEST_METHOD'] = 'POST';
  210. $event = new Event('Controller.startup', $this->Controller);
  211. $this->Controller->request['action'] = 'posted';
  212. $this->Controller->Security->requireSecure(array('posted'));
  213. $this->Controller->Security->startup($event);
  214. $this->assertTrue($this->Controller->failed);
  215. }
  216. /**
  217. * testRequireSecureSucceed method
  218. *
  219. * @return void
  220. */
  221. public function testRequireSecureSucceed() {
  222. $_SERVER['REQUEST_METHOD'] = 'Secure';
  223. $this->Controller->request['action'] = 'posted';
  224. $_SERVER['HTTPS'] = 'on';
  225. $event = new Event('Controller.startup', $this->Controller);
  226. $this->Controller->Security->requireSecure('posted');
  227. $this->Controller->Security->startup($event);
  228. $this->assertFalse($this->Controller->failed);
  229. }
  230. /**
  231. * testRequireAuthFail method
  232. *
  233. * @return void
  234. */
  235. public function testRequireAuthFail() {
  236. $event = new Event('Controller.startup', $this->Controller);
  237. $_SERVER['REQUEST_METHOD'] = 'AUTH';
  238. $this->Controller->request['action'] = 'posted';
  239. $this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass');
  240. $this->Controller->Security->requireAuth(array('posted'));
  241. $this->Controller->Security->startup($event);
  242. $this->assertTrue($this->Controller->failed);
  243. $this->Controller->Session->write('_Token', array('allowedControllers' => array()));
  244. $this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass');
  245. $this->Controller->request['action'] = 'posted';
  246. $this->Controller->Security->requireAuth('posted');
  247. $this->Controller->Security->startup($event);
  248. $this->assertTrue($this->Controller->failed);
  249. $this->Controller->Session->write('_Token', array(
  250. 'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted2')
  251. ));
  252. $this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass');
  253. $this->Controller->request['action'] = 'posted';
  254. $this->Controller->Security->requireAuth('posted');
  255. $this->Controller->Security->startup($event);
  256. $this->assertTrue($this->Controller->failed);
  257. }
  258. /**
  259. * testRequireAuthSucceed method
  260. *
  261. * @return void
  262. */
  263. public function testRequireAuthSucceed() {
  264. $_SERVER['REQUEST_METHOD'] = 'AUTH';
  265. $event = new Event('Controller.startup', $this->Controller);
  266. $this->Controller->request['action'] = 'posted';
  267. $this->Controller->Security->requireAuth('posted');
  268. $this->Controller->Security->startup($event);
  269. $this->assertFalse($this->Controller->failed);
  270. $this->Controller->Security->Session->write('_Token', array(
  271. 'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted')
  272. ));
  273. $this->Controller->request['controller'] = 'SecurityTest';
  274. $this->Controller->request['action'] = 'posted';
  275. $this->Controller->request->data = array(
  276. 'username' => 'willy', 'password' => 'somePass', '_Token' => ''
  277. );
  278. $this->Controller->action = 'posted';
  279. $this->Controller->Security->requireAuth('posted');
  280. $this->Controller->Security->startup($event);
  281. $this->assertFalse($this->Controller->failed);
  282. }
  283. /**
  284. * Simple hash validation test
  285. *
  286. * @return void
  287. */
  288. public function testValidatePost() {
  289. $event = new Event('Controller.startup', $this->Controller);
  290. $this->Controller->Security->startup($event);
  291. $key = $this->Controller->request->params['_Token']['key'];
  292. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  293. $unlocked = '';
  294. $this->Controller->request->data = array(
  295. 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
  296. '_Token' => compact('key', 'fields', 'unlocked')
  297. );
  298. $this->assertTrue($this->Controller->Security->validatePost($this->Controller));
  299. }
  300. /**
  301. * Test that validatePost fails if you are missing the session information.
  302. *
  303. * @return void
  304. */
  305. public function testValidatePostNoSession() {
  306. $event = new Event('Controller.startup', $this->Controller);
  307. $this->Controller->Security->startup($event);
  308. $this->Controller->Session->delete('_Token');
  309. $key = $this->Controller->request->params['_Token']['key'];
  310. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  311. $this->Controller->request->data = array(
  312. 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
  313. '_Token' => compact('key', 'fields')
  314. );
  315. $this->assertFalse($this->Controller->Security->validatePost($this->Controller));
  316. }
  317. /**
  318. * test that validatePost fails if any of its required fields are missing.
  319. *
  320. * @return void
  321. */
  322. public function testValidatePostFormHacking() {
  323. $event = new Event('Controller.startup', $this->Controller);
  324. $this->Controller->Security->startup($event);
  325. $key = $this->Controller->request->params['_Token']['key'];
  326. $unlocked = '';
  327. $this->Controller->request->data = array(
  328. 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
  329. '_Token' => compact('key', 'unlocked')
  330. );
  331. $result = $this->Controller->Security->validatePost($this->Controller);
  332. $this->assertFalse($result, 'validatePost passed when fields were missing. %s');
  333. }
  334. /**
  335. * Test that objects can't be passed into the serialized string. This was a vector for RFI and LFI
  336. * attacks. Thanks to Felix Wilhelm
  337. *
  338. * @return void
  339. */
  340. public function testValidatePostObjectDeserialize() {
  341. $event = new Event('Controller.startup', $this->Controller);
  342. $this->Controller->Security->startup($event);
  343. $key = $this->Controller->request->params['_Token']['key'];
  344. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877';
  345. $unlocked = '';
  346. // a corrupted serialized object, so we can see if it ever gets to deserialize
  347. $attack = 'O:3:"App":1:{s:5:"__map";a:1:{s:3:"foo";s:7:"Hacked!";s:1:"fail"}}';
  348. $fields .= urlencode(':' . str_rot13($attack));
  349. $this->Controller->request->data = array(
  350. 'Model' => array('username' => 'mark', 'password' => 'foo', 'valid' => '0'),
  351. '_Token' => compact('key', 'fields', 'unlocked')
  352. );
  353. $result = $this->Controller->Security->validatePost($this->Controller);
  354. $this->assertFalse($result, 'validatePost passed when key was missing. %s');
  355. }
  356. /**
  357. * Tests validation of checkbox arrays
  358. *
  359. * @return void
  360. */
  361. public function testValidatePostArray() {
  362. $event = new Event('Controller.startup', $this->Controller);
  363. $this->Controller->Security->startup($event);
  364. $key = $this->Controller->request->params['_Token']['key'];
  365. $fields = 'f7d573650a295b94e0938d32b323fde775e5f32b%3A';
  366. $unlocked = '';
  367. $this->Controller->request->data = array(
  368. 'Model' => array('multi_field' => array('1', '3')),
  369. '_Token' => compact('key', 'fields', 'unlocked')
  370. );
  371. $this->assertTrue($this->Controller->Security->validatePost($this->Controller));
  372. }
  373. /**
  374. * testValidatePostNoModel method
  375. *
  376. * @return void
  377. */
  378. public function testValidatePostNoModel() {
  379. $event = new Event('Controller.startup', $this->Controller);
  380. $this->Controller->Security->startup($event);
  381. $key = $this->Controller->request->params['_Token']['key'];
  382. $fields = '540ac9c60d323c22bafe997b72c0790f39a8bdef%3A';
  383. $unlocked = '';
  384. $this->Controller->request->data = array(
  385. 'anything' => 'some_data',
  386. '_Token' => compact('key', 'fields', 'unlocked')
  387. );
  388. $result = $this->Controller->Security->validatePost($this->Controller);
  389. $this->assertTrue($result);
  390. }
  391. /**
  392. * testValidatePostSimple method
  393. *
  394. * @return void
  395. */
  396. public function testValidatePostSimple() {
  397. $event = new Event('Controller.startup', $this->Controller);
  398. $this->Controller->Security->startup($event);
  399. $key = $this->Controller->request->params['_Token']['key'];
  400. $fields = '69f493434187b867ea14b901fdf58b55d27c935d%3A';
  401. $unlocked = '';
  402. $this->Controller->request->data = $data = array(
  403. 'Model' => array('username' => '', 'password' => ''),
  404. '_Token' => compact('key', 'fields', 'unlocked')
  405. );
  406. $result = $this->Controller->Security->validatePost($this->Controller);
  407. $this->assertTrue($result);
  408. }
  409. /**
  410. * Tests hash validation for multiple records, including locked fields
  411. *
  412. * @return void
  413. */
  414. public function testValidatePostComplex() {
  415. $event = new Event('Controller.startup', $this->Controller);
  416. $this->Controller->Security->startup($event);
  417. $key = $this->Controller->request->params['_Token']['key'];
  418. $fields = 'c9118120e680a7201b543f562e5301006ccfcbe2%3AAddresses.0.id%7CAddresses.1.id';
  419. $unlocked = '';
  420. $this->Controller->request->data = array(
  421. 'Addresses' => array(
  422. '0' => array(
  423. 'id' => '123456', 'title' => '', 'first_name' => '', 'last_name' => '',
  424. 'address' => '', 'city' => '', 'phone' => '', 'primary' => ''
  425. ),
  426. '1' => array(
  427. 'id' => '654321', 'title' => '', 'first_name' => '', 'last_name' => '',
  428. 'address' => '', 'city' => '', 'phone' => '', 'primary' => ''
  429. )
  430. ),
  431. '_Token' => compact('key', 'fields', 'unlocked')
  432. );
  433. $result = $this->Controller->Security->validatePost($this->Controller);
  434. $this->assertTrue($result);
  435. }
  436. /**
  437. * test ValidatePost with multiple select elements.
  438. *
  439. * @return void
  440. */
  441. public function testValidatePostMultipleSelect() {
  442. $event = new Event('Controller.startup', $this->Controller);
  443. $this->Controller->Security->startup($event);
  444. $key = $this->Controller->request->params['_Token']['key'];
  445. $fields = '422cde416475abc171568be690a98cad20e66079%3A';
  446. $unlocked = '';
  447. $this->Controller->request->data = array(
  448. 'Tag' => array('Tag' => array(1, 2)),
  449. '_Token' => compact('key', 'fields', 'unlocked'),
  450. );
  451. $result = $this->Controller->Security->validatePost($this->Controller);
  452. $this->assertTrue($result);
  453. $this->Controller->request->data = array(
  454. 'Tag' => array('Tag' => array(1, 2, 3)),
  455. '_Token' => compact('key', 'fields', 'unlocked'),
  456. );
  457. $result = $this->Controller->Security->validatePost($this->Controller);
  458. $this->assertTrue($result);
  459. $this->Controller->request->data = array(
  460. 'Tag' => array('Tag' => array(1, 2, 3, 4)),
  461. '_Token' => compact('key', 'fields', 'unlocked'),
  462. );
  463. $result = $this->Controller->Security->validatePost($this->Controller);
  464. $this->assertTrue($result);
  465. $fields = '19464422eafe977ee729c59222af07f983010c5f%3A';
  466. $this->Controller->request->data = array(
  467. 'User.password' => 'bar', 'User.name' => 'foo', 'User.is_valid' => '1',
  468. 'Tag' => array('Tag' => array(1)),
  469. '_Token' => compact('key', 'fields', 'unlocked'),
  470. );
  471. $result = $this->Controller->Security->validatePost($this->Controller);
  472. $this->assertTrue($result);
  473. }
  474. /**
  475. * testValidatePostCheckbox method
  476. *
  477. * First block tests un-checked checkbox
  478. * Second block tests checked checkbox
  479. *
  480. * @return void
  481. */
  482. public function testValidatePostCheckbox() {
  483. $event = new Event('Controller.startup', $this->Controller);
  484. $this->Controller->Security->startup($event);
  485. $key = $this->Controller->request->params['_Token']['key'];
  486. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  487. $unlocked = '';
  488. $this->Controller->request->data = array(
  489. 'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
  490. '_Token' => compact('key', 'fields', 'unlocked')
  491. );
  492. $result = $this->Controller->Security->validatePost($this->Controller);
  493. $this->assertTrue($result);
  494. $fields = '874439ca69f89b4c4a5f50fb9c36ff56a28f5d42%3A';
  495. $this->Controller->request->data = array(
  496. 'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
  497. '_Token' => compact('key', 'fields', 'unlocked')
  498. );
  499. $result = $this->Controller->Security->validatePost($this->Controller);
  500. $this->assertTrue($result);
  501. $this->Controller->request->data = array();
  502. $this->Controller->Security->startup($event);
  503. $key = $this->Controller->request->params['_Token']['key'];
  504. $this->Controller->request->data = array(
  505. 'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
  506. '_Token' => compact('key', 'fields', 'unlocked')
  507. );
  508. $result = $this->Controller->Security->validatePost($this->Controller);
  509. $this->assertTrue($result);
  510. }
  511. /**
  512. * testValidatePostHidden method
  513. *
  514. * @return void
  515. */
  516. public function testValidatePostHidden() {
  517. $event = new Event('Controller.startup', $this->Controller);
  518. $this->Controller->Security->startup($event);
  519. $key = $this->Controller->request->params['_Token']['key'];
  520. $fields = '51ccd8cb0997c7b3d4523ecde5a109318405ef8c%3AModel.hidden%7CModel.other_hidden';
  521. $unlocked = '';
  522. $this->Controller->request->data = array(
  523. 'Model' => array(
  524. 'username' => '', 'password' => '', 'hidden' => '0',
  525. 'other_hidden' => 'some hidden value'
  526. ),
  527. '_Token' => compact('key', 'fields', 'unlocked')
  528. );
  529. $result = $this->Controller->Security->validatePost($this->Controller);
  530. $this->assertTrue($result);
  531. }
  532. /**
  533. * testValidatePostWithDisabledFields method
  534. *
  535. * @return void
  536. */
  537. public function testValidatePostWithDisabledFields() {
  538. $event = new Event('Controller.startup', $this->Controller);
  539. $this->Controller->Security->disabledFields = array('Model.username', 'Model.password');
  540. $this->Controller->Security->startup($event);
  541. $key = $this->Controller->request->params['_Token']['key'];
  542. $fields = 'ef1082968c449397bcd849f963636864383278b1%3AModel.hidden';
  543. $unlocked = '';
  544. $this->Controller->request->data = array(
  545. 'Model' => array(
  546. 'username' => '', 'password' => '', 'hidden' => '0'
  547. ),
  548. '_Token' => compact('fields', 'key', 'unlocked')
  549. );
  550. $result = $this->Controller->Security->validatePost($this->Controller);
  551. $this->assertTrue($result);
  552. }
  553. /**
  554. * test validating post data with posted unlocked fields.
  555. *
  556. * @return void
  557. */
  558. public function testValidatePostDisabledFieldsInData() {
  559. $event = new Event('Controller.startup', $this->Controller);
  560. $this->Controller->Security->startup($event);
  561. $key = $this->Controller->request->params['_Token']['key'];
  562. $unlocked = 'Model.username';
  563. $fields = array('Model.hidden', 'Model.password');
  564. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt')));
  565. $this->Controller->request->data = array(
  566. 'Model' => array(
  567. 'username' => 'mark',
  568. 'password' => 'sekret',
  569. 'hidden' => '0'
  570. ),
  571. '_Token' => compact('fields', 'key', 'unlocked')
  572. );
  573. $result = $this->Controller->Security->validatePost($this->Controller);
  574. $this->assertTrue($result);
  575. }
  576. /**
  577. * test that missing 'unlocked' input causes failure
  578. *
  579. * @return void
  580. */
  581. public function testValidatePostFailNoDisabled() {
  582. $event = new Event('Controller.startup', $this->Controller);
  583. $this->Controller->Security->startup($event);
  584. $key = $this->Controller->request->params['_Token']['key'];
  585. $fields = array('Model.hidden', 'Model.password', 'Model.username');
  586. $fields = urlencode(Security::hash(serialize($fields) . Configure::read('Security.salt')));
  587. $this->Controller->request->data = array(
  588. 'Model' => array(
  589. 'username' => 'mark',
  590. 'password' => 'sekret',
  591. 'hidden' => '0'
  592. ),
  593. '_Token' => compact('fields', 'key')
  594. );
  595. $result = $this->Controller->Security->validatePost($this->Controller);
  596. $this->assertFalse($result);
  597. }
  598. /**
  599. * Test that validatePost fails when unlocked fields are changed.
  600. *
  601. * @return
  602. */
  603. public function testValidatePostFailDisabledFieldTampering() {
  604. $event = new Event('Controller.startup', $this->Controller);
  605. $this->Controller->Security->startup($event);
  606. $key = $this->Controller->request->params['_Token']['key'];
  607. $unlocked = 'Model.username';
  608. $fields = array('Model.hidden', 'Model.password');
  609. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt')));
  610. // Tamper the values.
  611. $unlocked = 'Model.username|Model.password';
  612. $this->Controller->request->data = array(
  613. 'Model' => array(
  614. 'username' => 'mark',
  615. 'password' => 'sekret',
  616. 'hidden' => '0'
  617. ),
  618. '_Token' => compact('fields', 'key', 'unlocked')
  619. );
  620. $result = $this->Controller->Security->validatePost($this->Controller);
  621. $this->assertFalse($result);
  622. }
  623. /**
  624. * testValidateHiddenMultipleModel method
  625. *
  626. * @return void
  627. */
  628. public function testValidateHiddenMultipleModel() {
  629. $event = new Event('Controller.startup', $this->Controller);
  630. $this->Controller->Security->startup($event);
  631. $key = $this->Controller->request->params['_Token']['key'];
  632. $fields = 'a2d01072dc4660eea9d15007025f35a7a5b58e18%3AModel.valid%7CModel2.valid%7CModel3.valid';
  633. $unlocked = '';
  634. $this->Controller->request->data = array(
  635. 'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
  636. 'Model2' => array('valid' => '0'),
  637. 'Model3' => array('valid' => '0'),
  638. '_Token' => compact('key', 'fields', 'unlocked')
  639. );
  640. $result = $this->Controller->Security->validatePost($this->Controller);
  641. $this->assertTrue($result);
  642. }
  643. /**
  644. * testValidateHasManyModel method
  645. *
  646. * @return void
  647. */
  648. public function testValidateHasManyModel() {
  649. $event = new Event('Controller.startup', $this->Controller);
  650. $this->Controller->Security->startup($event);
  651. $key = $this->Controller->request->params['_Token']['key'];
  652. $fields = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3AModel.0.hidden%7CModel.0.valid';
  653. $fields .= '%7CModel.1.hidden%7CModel.1.valid';
  654. $unlocked = '';
  655. $this->Controller->request->data = array(
  656. 'Model' => array(
  657. array(
  658. 'username' => 'username', 'password' => 'password',
  659. 'hidden' => 'value', 'valid' => '0'
  660. ),
  661. array(
  662. 'username' => 'username', 'password' => 'password',
  663. 'hidden' => 'value', 'valid' => '0'
  664. )
  665. ),
  666. '_Token' => compact('key', 'fields', 'unlocked')
  667. );
  668. $result = $this->Controller->Security->validatePost($this->Controller);
  669. $this->assertTrue($result);
  670. }
  671. /**
  672. * testValidateHasManyRecordsPass method
  673. *
  674. * @return void
  675. */
  676. public function testValidateHasManyRecordsPass() {
  677. $event = new Event('Controller.startup', $this->Controller);
  678. $this->Controller->Security->startup($event);
  679. $key = $this->Controller->request->params['_Token']['key'];
  680. $fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C';
  681. $fields .= 'Address.1.id%7CAddress.1.primary';
  682. $unlocked = '';
  683. $this->Controller->request->data = array(
  684. 'Address' => array(
  685. 0 => array(
  686. 'id' => '123',
  687. 'title' => 'home',
  688. 'first_name' => 'Bilbo',
  689. 'last_name' => 'Baggins',
  690. 'address' => '23 Bag end way',
  691. 'city' => 'the shire',
  692. 'phone' => 'N/A',
  693. 'primary' => '1',
  694. ),
  695. 1 => array(
  696. 'id' => '124',
  697. 'title' => 'home',
  698. 'first_name' => 'Frodo',
  699. 'last_name' => 'Baggins',
  700. 'address' => '50 Bag end way',
  701. 'city' => 'the shire',
  702. 'phone' => 'N/A',
  703. 'primary' => '1'
  704. )
  705. ),
  706. '_Token' => compact('key', 'fields', 'unlocked')
  707. );
  708. $result = $this->Controller->Security->validatePost($this->Controller);
  709. $this->assertTrue($result);
  710. }
  711. /**
  712. * Test that values like Foo.0.1
  713. *
  714. * @return void
  715. */
  716. public function testValidateNestedNumericSets() {
  717. $event = new Event('Controller.startup', $this->Controller);
  718. $this->Controller->Security->startup($event);
  719. $key = $this->Controller->request->params['_Token']['key'];
  720. $unlocked = '';
  721. $hashFields = array('TaxonomyData');
  722. $fields = urlencode(Security::hash(serialize($hashFields) . $unlocked . Configure::read('Security.salt')));
  723. $this->Controller->request->data = array(
  724. 'TaxonomyData' => array(
  725. 1 => array(array(2)),
  726. 2 => array(array(3))
  727. ),
  728. '_Token' => compact('key', 'fields', 'unlocked')
  729. );
  730. $result = $this->Controller->Security->validatePost($this->Controller);
  731. $this->assertTrue($result);
  732. }
  733. /**
  734. * testValidateHasManyRecords method
  735. *
  736. * validatePost should fail, hidden fields have been changed.
  737. *
  738. * @return void
  739. */
  740. public function testValidateHasManyRecordsFail() {
  741. $event = new Event('Controller.startup', $this->Controller);
  742. $this->Controller->Security->startup($event);
  743. $key = $this->Controller->request->params['_Token']['key'];
  744. $fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C';
  745. $fields .= 'Address.1.id%7CAddress.1.primary';
  746. $unlocked = '';
  747. $this->Controller->request->data = array(
  748. 'Address' => array(
  749. 0 => array(
  750. 'id' => '123',
  751. 'title' => 'home',
  752. 'first_name' => 'Bilbo',
  753. 'last_name' => 'Baggins',
  754. 'address' => '23 Bag end way',
  755. 'city' => 'the shire',
  756. 'phone' => 'N/A',
  757. 'primary' => '5',
  758. ),
  759. 1 => array(
  760. 'id' => '124',
  761. 'title' => 'home',
  762. 'first_name' => 'Frodo',
  763. 'last_name' => 'Baggins',
  764. 'address' => '50 Bag end way',
  765. 'city' => 'the shire',
  766. 'phone' => 'N/A',
  767. 'primary' => '1'
  768. )
  769. ),
  770. '_Token' => compact('key', 'fields', 'unlocked')
  771. );
  772. $result = $this->Controller->Security->validatePost($this->Controller);
  773. $this->assertFalse($result);
  774. }
  775. /**
  776. * testFormDisabledFields method
  777. *
  778. * @return void
  779. */
  780. public function testFormDisabledFields() {
  781. $event = new Event('Controller.startup', $this->Controller);
  782. $this->Controller->Security->startup($event);
  783. $key = $this->Controller->request->params['_Token']['key'];
  784. $fields = '11842060341b9d0fc3808b90ba29fdea7054d6ad%3An%3A0%3A%7B%7D';
  785. $unlocked = '';
  786. $this->Controller->request->data = array(
  787. 'MyModel' => array('name' => 'some data'),
  788. '_Token' => compact('key', 'fields', 'unlocked')
  789. );
  790. $result = $this->Controller->Security->validatePost($this->Controller);
  791. $this->assertFalse($result);
  792. $this->Controller->Security->startup($event);
  793. $this->Controller->Security->disabledFields = array('MyModel.name');
  794. $key = $this->Controller->request->params['_Token']['key'];
  795. $this->Controller->request->data = array(
  796. 'MyModel' => array('name' => 'some data'),
  797. '_Token' => compact('key', 'fields', 'unlocked')
  798. );
  799. $result = $this->Controller->Security->validatePost($this->Controller);
  800. $this->assertTrue($result);
  801. }
  802. /**
  803. * testRadio method
  804. *
  805. * @return void
  806. */
  807. public function testRadio() {
  808. $event = new Event('Controller.startup', $this->Controller);
  809. $this->Controller->Security->startup($event);
  810. $key = $this->Controller->request->params['_Token']['key'];
  811. $fields = '575ef54ca4fc8cab468d6d898e9acd3a9671c17e%3An%3A0%3A%7B%7D';
  812. $unlocked = '';
  813. $this->Controller->request->data = array(
  814. '_Token' => compact('key', 'fields', 'unlocked')
  815. );
  816. $result = $this->Controller->Security->validatePost($this->Controller);
  817. $this->assertFalse($result);
  818. $this->Controller->request->data = array(
  819. '_Token' => compact('key', 'fields', 'unlocked'),
  820. 'Test' => array('test' => '')
  821. );
  822. $result = $this->Controller->Security->validatePost($this->Controller);
  823. $this->assertTrue($result);
  824. $this->Controller->request->data = array(
  825. '_Token' => compact('key', 'fields', 'unlocked'),
  826. 'Test' => array('test' => '1')
  827. );
  828. $result = $this->Controller->Security->validatePost($this->Controller);
  829. $this->assertTrue($result);
  830. $this->Controller->request->data = array(
  831. '_Token' => compact('key', 'fields', 'unlocked'),
  832. 'Test' => array('test' => '2')
  833. );
  834. $result = $this->Controller->Security->validatePost($this->Controller);
  835. $this->assertTrue($result);
  836. }
  837. /**
  838. * test that a requestAction's controller will have the _Token appended to
  839. * the params.
  840. *
  841. * @return void
  842. * @see https://cakephp.lighthouseapp.com/projects/42648/tickets/68
  843. */
  844. public function testSettingTokenForRequestAction() {
  845. $event = new Event('Controller.startup', $this->Controller);
  846. $this->Controller->Security->startup($event);
  847. $key = $this->Controller->request->params['_Token']['key'];
  848. $this->Controller->request->params['requested'] = 1;
  849. unset($this->Controller->request->params['_Token']);
  850. $this->Controller->Security->startup($event);
  851. $this->assertEquals($this->Controller->request->params['_Token']['key'], $key);
  852. }
  853. /**
  854. * test that blackhole doesn't delete the _Token session key so repeat data submissions
  855. * stay blackholed.
  856. *
  857. * @link https://cakephp.lighthouseapp.com/projects/42648/tickets/214
  858. * @return void
  859. */
  860. public function testBlackHoleNotDeletingSessionInformation() {
  861. $event = new Event('Controller.startup', $this->Controller);
  862. $this->Controller->Security->startup($event);
  863. $this->Controller->Security->blackHole($this->Controller, 'auth');
  864. $this->assertTrue($this->Controller->Security->Session->check('_Token'), '_Token was deleted by blackHole %s');
  865. }
  866. /**
  867. * test that csrf checks are skipped for request action.
  868. *
  869. * @return void
  870. */
  871. public function testCsrfSkipRequestAction() {
  872. $_SERVER['REQUEST_METHOD'] = 'POST';
  873. $event = new Event('Controller.startup', $this->Controller);
  874. $this->Security->validatePost = false;
  875. $this->Security->csrfCheck = true;
  876. $this->Security->csrfExpires = '+10 minutes';
  877. $this->Controller->request->params['requested'] = 1;
  878. $this->Security->startup($event);
  879. $this->assertFalse($this->Controller->failed, 'fail() was called.');
  880. }
  881. /**
  882. * test setting
  883. *
  884. * @return void
  885. */
  886. public function testCsrfSettings() {
  887. $this->Security->validatePost = false;
  888. $this->Security->csrfCheck = true;
  889. $this->Security->csrfExpires = '+10 minutes';
  890. $event = new Event('Controller.startup', $this->Controller);
  891. $this->Security->startup($event);
  892. $token = $this->Security->Session->read('_Token');
  893. $this->assertEquals(1, count($token['csrfTokens']), 'Missing the csrf token.');
  894. $this->assertEquals(strtotime('+10 minutes'), current($token['csrfTokens']), 'Token expiry does not match');
  895. $this->assertEquals(array('key', 'unlockedFields'), array_keys($this->Controller->request->params['_Token']), 'Keys don not match');
  896. }
  897. /**
  898. * Test setting multiple nonces, when startup() is called more than once, (ie more than one request.)
  899. *
  900. * @return void
  901. */
  902. public function testCsrfSettingMultipleNonces() {
  903. $this->Security->validatePost = false;
  904. $this->Security->csrfCheck = true;
  905. $this->Security->csrfExpires = '+10 minutes';
  906. $csrfExpires = strtotime('+10 minutes');
  907. $event = new Event('Controller.startup', $this->Controller);
  908. $this->Security->startup($event);
  909. $this->Security->startup($event);
  910. $token = $this->Security->Session->read('_Token');
  911. $this->assertEquals(2, count($token['csrfTokens']), 'Missing the csrf token.');
  912. foreach ($token['csrfTokens'] as $expires) {
  913. $diff = $csrfExpires - $expires;
  914. $this->assertTrue($diff === 0 || $diff === 1, 'Token expiry does not match');
  915. }
  916. }
  917. /**
  918. * test that nonces are consumed by form submits.
  919. *
  920. * @return void
  921. */
  922. public function testCsrfNonceConsumption() {
  923. $this->Security->validatePost = false;
  924. $this->Security->csrfCheck = true;
  925. $this->Security->csrfExpires = '+10 minutes';
  926. $event = new Event('Controller.startup', $this->Controller);
  927. $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes')));
  928. $this->Controller->request = $this->getMock('Cake\Network\Request', array('is'));
  929. $this->Controller->request->expects($this->once())->method('is')
  930. ->with(array('post', 'put'))
  931. ->will($this->returnValue(true));
  932. $this->Controller->request->params['action'] = 'index';
  933. $this->Controller->request->data = array(
  934. '_Token' => array(
  935. 'key' => 'nonce1'
  936. ),
  937. 'Post' => array(
  938. 'title' => 'Woot'
  939. )
  940. );
  941. $this->Security->startup($event);
  942. $token = $this->Security->Session->read('_Token');
  943. $this->assertFalse(isset($token['csrfTokens']['nonce1']), 'Token was not consumed');
  944. }
  945. /**
  946. * test that expired values in the csrfTokens are cleaned up.
  947. *
  948. * @return void
  949. */
  950. public function testCsrfNonceVacuum() {
  951. $this->Security->validatePost = false;
  952. $this->Security->csrfCheck = true;
  953. $this->Security->csrfExpires = '+10 minutes';
  954. $event = new Event('Controller.startup', $this->Controller);
  955. $this->Security->Session->write('_Token.csrfTokens', array(
  956. 'valid' => strtotime('+30 minutes'),
  957. 'poof' => strtotime('-11 minutes'),
  958. 'dust' => strtotime('-20 minutes')
  959. ));
  960. $this->Security->startup($event);
  961. $tokens = $this->Security->Session->read('_Token.csrfTokens');
  962. $this->assertEquals(2, count($tokens), 'Too many tokens left behind');
  963. $this->assertNotEmpty('valid', $tokens, 'Valid token was removed.');
  964. }
  965. /**
  966. * test that when the key is missing the request is blackHoled
  967. *
  968. * @return void
  969. */
  970. public function testCsrfBlackHoleOnKeyMismatch() {
  971. $this->Security->validatePost = false;
  972. $this->Security->csrfCheck = true;
  973. $this->Security->csrfExpires = '+10 minutes';
  974. $event = new Event('Controller.startup', $this->Controller);
  975. $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes')));
  976. $this->Controller->request = $this->getMock('Cake\Network\Request', array('is'));
  977. $this->Controller->request->expects($this->once())->method('is')
  978. ->with(array('post', 'put'))
  979. ->will($this->returnValue(true));
  980. $this->Controller->request->params['action'] = 'index';
  981. $this->Controller->request->data = array(
  982. '_Token' => array(
  983. 'key' => 'not the right value'
  984. ),
  985. 'Post' => array(
  986. 'title' => 'Woot'
  987. )
  988. );
  989. $this->Security->startup($event);
  990. $this->assertTrue($this->Controller->failed, 'fail() was not called.');
  991. }
  992. /**
  993. * test that when the key is missing the request is blackHoled
  994. *
  995. * @return void
  996. */
  997. public function testCsrfBlackHoleOnExpiredKey() {
  998. $this->Security->validatePost = false;
  999. $this->Security->csrfCheck = true;
  1000. $this->Security->csrfExpires = '+10 minutes';
  1001. $event = new Event('Controller.startup', $this->Controller);
  1002. $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('-5 minutes')));
  1003. $this->Controller->request = $this->getMock('Cake\Network\Request', array('is'));
  1004. $this->Controller->request->expects($this->once())->method('is')
  1005. ->with(array('post', 'put'))
  1006. ->will($this->returnValue(true));
  1007. $this->Controller->request->params['action'] = 'index';
  1008. $this->Controller->request->data = array(
  1009. '_Token' => array(
  1010. 'key' => 'nonce1'
  1011. ),
  1012. 'Post' => array(
  1013. 'title' => 'Woot'
  1014. )
  1015. );
  1016. $this->Security->startup($event);
  1017. $this->assertTrue($this->Controller->failed, 'fail() was not called.');
  1018. }
  1019. /**
  1020. * test that csrfUseOnce = false works.
  1021. *
  1022. * @return void
  1023. */
  1024. public function testCsrfNotUseOnce() {
  1025. $this->Security->validatePost = false;
  1026. $this->Security->csrfCheck = true;
  1027. $this->Security->csrfUseOnce = false;
  1028. $this->Security->csrfExpires = '+10 minutes';
  1029. $event = new Event('Controller.startup', $this->Controller);
  1030. // Generate one token
  1031. $this->Security->startup($event);
  1032. $token = $this->Security->Session->read('_Token.csrfTokens');
  1033. $this->assertEquals(1, count($token), 'Should only be one token.');
  1034. $this->Security->startup($event);
  1035. $tokenTwo = $this->Security->Session->read('_Token.csrfTokens');
  1036. $this->assertEquals(1, count($tokenTwo), 'Should only be one token.');
  1037. $this->assertEquals($token, $tokenTwo, 'Tokens should not be different.');
  1038. $key = $this->Controller->request->params['_Token']['key'];
  1039. $this->assertEquals(array($key), array_keys($token), '_Token.key and csrfToken do not match request will blackhole.');
  1040. }
  1041. /**
  1042. * ensure that longer session tokens are not consumed
  1043. *
  1044. * @return void
  1045. */
  1046. public function testCsrfNotUseOnceValidationLeavingToken() {
  1047. $this->Security->validatePost = false;
  1048. $this->Security->csrfCheck = true;
  1049. $this->Security->csrfUseOnce = false;
  1050. $this->Security->csrfExpires = '+10 minutes';
  1051. $event = new Event('Controller.startup', $this->Controller);
  1052. $this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes')));
  1053. $this->Controller->request = $this->getMock('Cake\Network\Request', array('is'));
  1054. $this->Controller->request->expects($this->once())->method('is')
  1055. ->with(array('post', 'put'))
  1056. ->will($this->returnValue(true));
  1057. $this->Controller->request->params['action'] = 'index';
  1058. $this->Controller->request->data = array(
  1059. '_Token' => array(
  1060. 'key' => 'nonce1'
  1061. ),
  1062. 'Post' => array(
  1063. 'title' => 'Woot'
  1064. )
  1065. );
  1066. $this->Security->startup($event);
  1067. $token = $this->Security->Session->read('_Token');
  1068. $this->assertTrue(isset($token['csrfTokens']['nonce1']), 'Token was consumed');
  1069. }
  1070. /**
  1071. * Test generateToken()
  1072. *
  1073. * @return void
  1074. */
  1075. public function testGenerateToken() {
  1076. $request = $this->Controller->request;
  1077. $this->Security->generateToken($request);
  1078. $this->assertNotEmpty($request->params['_Token']);
  1079. $this->assertTrue(isset($request->params['_Token']['unlockedFields']));
  1080. $this->assertTrue(isset($request->params['_Token']['key']));
  1081. }
  1082. /**
  1083. * Test the limiting of CSRF tokens.
  1084. *
  1085. * @return void
  1086. */
  1087. public function testCsrfLimit() {
  1088. $this->Security->csrfLimit = 3;
  1089. $time = strtotime('+10 minutes');
  1090. $tokens = array(
  1091. '1' => $time,
  1092. '2' => $time,
  1093. '3' => $time,
  1094. '4' => $time,
  1095. '5' => $time,
  1096. );
  1097. $this->Security->Session->write('_Token', array('csrfTokens' => $tokens));
  1098. $this->Security->generateToken($this->Controller->request);
  1099. $result = $this->Security->Session->read('_Token.csrfTokens');
  1100. $this->assertFalse(isset($result['1']));
  1101. $this->assertFalse(isset($result['2']));
  1102. $this->assertFalse(isset($result['3']));
  1103. $this->assertTrue(isset($result['4']));
  1104. $this->assertTrue(isset($result['5']));
  1105. }
  1106. /**
  1107. * Test unlocked actions
  1108. *
  1109. * @return void
  1110. */
  1111. public function testUnlockedActions() {
  1112. $_SERVER['REQUEST_METHOD'] = 'POST';
  1113. $event = new Event('Controller.startup', $this->Controller);
  1114. $this->Controller->request->data = array('data');
  1115. $this->Controller->Security->unlockedActions = 'index';
  1116. $this->Controller->Security->blackHoleCallback = null;
  1117. $result = $this->Controller->Security->startup($event);
  1118. $this->assertNull($result);
  1119. }
  1120. }