1
0

CryptTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OCA\Encryption\Tests\Crypto;
  28. use OCA\Encryption\Crypto\Crypt;
  29. use OCP\IConfig;
  30. use OCP\IL10N;
  31. use OCP\ILogger;
  32. use OCP\IUserSession;
  33. use Test\TestCase;
  34. class CryptTest extends TestCase {
  35. /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */
  36. private $logger;
  37. /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */
  38. private $userSession;
  39. /** @var \OCP\IConfig|\PHPUnit_Framework_MockObject_MockObject */
  40. private $config;
  41. /** @var \OCP\IL10N|\PHPUnit_Framework_MockObject_MockObject */
  42. private $l;
  43. /** @var Crypt */
  44. private $crypt;
  45. public function setUp() {
  46. parent::setUp();
  47. $this->logger = $this->getMockBuilder(ILogger::class)
  48. ->disableOriginalConstructor()
  49. ->getMock();
  50. $this->logger->expects($this->any())
  51. ->method('warning')
  52. ->willReturn(true);
  53. $this->userSession = $this->getMockBuilder(IUserSession::class)
  54. ->disableOriginalConstructor()
  55. ->getMock();
  56. $this->config = $this->getMockBuilder(IConfig::class)
  57. ->disableOriginalConstructor()
  58. ->getMock();
  59. $this->l = $this->createMock(IL10N::class);
  60. $this->crypt = new Crypt($this->logger, $this->userSession, $this->config, $this->l);
  61. }
  62. /**
  63. * test getOpenSSLConfig without any additional parameters
  64. */
  65. public function testGetOpenSSLConfigBasic() {
  66. $this->config->expects($this->once())
  67. ->method('getSystemValue')
  68. ->with($this->equalTo('openssl'), $this->equalTo([]))
  69. ->willReturn(array());
  70. $result = self::invokePrivate($this->crypt, 'getOpenSSLConfig');
  71. $this->assertSame(1, count($result));
  72. $this->assertArrayHasKey('private_key_bits', $result);
  73. $this->assertSame(4096, $result['private_key_bits']);
  74. }
  75. /**
  76. * test getOpenSSLConfig with additional parameters defined in config.php
  77. */
  78. public function testGetOpenSSLConfig() {
  79. $this->config->expects($this->once())
  80. ->method('getSystemValue')
  81. ->with($this->equalTo('openssl'), $this->equalTo([]))
  82. ->willReturn(array('foo' => 'bar', 'private_key_bits' => 1028));
  83. $result = self::invokePrivate($this->crypt, 'getOpenSSLConfig');
  84. $this->assertSame(2, count($result));
  85. $this->assertArrayHasKey('private_key_bits', $result);
  86. $this->assertArrayHasKey('foo', $result);
  87. $this->assertSame(1028, $result['private_key_bits']);
  88. $this->assertSame('bar', $result['foo']);
  89. }
  90. /**
  91. * test generateHeader with valid key formats
  92. *
  93. * @dataProvider dataTestGenerateHeader
  94. */
  95. public function testGenerateHeader($keyFormat, $expected) {
  96. $this->config->expects($this->once())
  97. ->method('getSystemValue')
  98. ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR'))
  99. ->willReturn('AES-128-CFB');
  100. if ($keyFormat) {
  101. $result = $this->crypt->generateHeader($keyFormat);
  102. } else {
  103. $result = $this->crypt->generateHeader();
  104. }
  105. $this->assertSame($expected, $result);
  106. }
  107. /**
  108. * test generateHeader with invalid key format
  109. *
  110. * @expectedException \InvalidArgumentException
  111. */
  112. public function testGenerateHeaderInvalid() {
  113. $this->crypt->generateHeader('unknown');
  114. }
  115. /**
  116. * @return array
  117. */
  118. public function dataTestGenerateHeader() {
  119. return [
  120. [null, 'HBEGIN:cipher:AES-128-CFB:keyFormat:hash:HEND'],
  121. ['password', 'HBEGIN:cipher:AES-128-CFB:keyFormat:password:HEND'],
  122. ['hash', 'HBEGIN:cipher:AES-128-CFB:keyFormat:hash:HEND']
  123. ];
  124. }
  125. public function testGetCipherWithInvalidCipher() {
  126. $this->config->expects($this->once())
  127. ->method('getSystemValue')
  128. ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR'))
  129. ->willReturn('Not-Existing-Cipher');
  130. $this->logger
  131. ->expects($this->once())
  132. ->method('warning')
  133. ->with('Unsupported cipher (Not-Existing-Cipher) defined in config.php supported. Falling back to AES-256-CTR');
  134. $this->assertSame('AES-256-CTR', $this->crypt->getCipher());
  135. }
  136. /**
  137. * @dataProvider dataProviderGetCipher
  138. * @param string $configValue
  139. * @param string $expected
  140. */
  141. public function testGetCipher($configValue, $expected) {
  142. $this->config->expects($this->once())
  143. ->method('getSystemValue')
  144. ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR'))
  145. ->willReturn($configValue);
  146. $this->assertSame($expected,
  147. $this->crypt->getCipher()
  148. );
  149. }
  150. /**
  151. * data provider for testGetCipher
  152. *
  153. * @return array
  154. */
  155. public function dataProviderGetCipher() {
  156. return array(
  157. array('AES-128-CFB', 'AES-128-CFB'),
  158. array('AES-256-CFB', 'AES-256-CFB'),
  159. array('AES-128-CTR', 'AES-128-CTR'),
  160. array('AES-256-CTR', 'AES-256-CTR'),
  161. array('unknown', 'AES-256-CTR')
  162. );
  163. }
  164. /**
  165. * test concatIV()
  166. */
  167. public function testConcatIV() {
  168. $result = self::invokePrivate(
  169. $this->crypt,
  170. 'concatIV',
  171. array('content', 'my_iv'));
  172. $this->assertSame('content00iv00my_iv',
  173. $result
  174. );
  175. }
  176. /**
  177. * @dataProvider dataTestSplitMetaData
  178. */
  179. public function testSplitMetaData($data, $expected) {
  180. $result = self::invokePrivate($this->crypt, 'splitMetaData', array($data, 'AES-256-CFB'));
  181. $this->assertTrue(is_array($result));
  182. $this->assertSame(3, count($result));
  183. $this->assertArrayHasKey('encrypted', $result);
  184. $this->assertArrayHasKey('iv', $result);
  185. $this->assertArrayHasKey('signature', $result);
  186. $this->assertSame($expected['encrypted'], $result['encrypted']);
  187. $this->assertSame($expected['iv'], $result['iv']);
  188. $this->assertSame($expected['signature'], $result['signature']);
  189. }
  190. public function dataTestSplitMetaData() {
  191. return [
  192. ['encryptedContent00iv001234567890123456xx',
  193. ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => false]],
  194. ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx',
  195. ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => 'e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86']],
  196. ];
  197. }
  198. /**
  199. * @dataProvider dataTestHasSignature
  200. */
  201. public function testHasSignature($data, $expected) {
  202. $this->assertSame($expected,
  203. $this->invokePrivate($this->crypt, 'hasSignature', array($data, 'AES-256-CFB'))
  204. );
  205. }
  206. public function dataTestHasSignature() {
  207. return [
  208. ['encryptedContent00iv001234567890123456xx', false],
  209. ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx', true]
  210. ];
  211. }
  212. /**
  213. * @dataProvider dataTestHasSignatureFail
  214. * @expectedException \OCP\Encryption\Exceptions\GenericEncryptionException
  215. */
  216. public function testHasSignatureFail($cipher) {
  217. $data = 'encryptedContent00iv001234567890123456xx';
  218. $this->invokePrivate($this->crypt, 'hasSignature', array($data, $cipher));
  219. }
  220. public function dataTestHasSignatureFail() {
  221. return [
  222. ['AES-256-CTR'],
  223. ['aes-256-ctr'],
  224. ['AES-128-CTR'],
  225. ['ctr-256-ctr']
  226. ];
  227. }
  228. /**
  229. * test addPadding()
  230. */
  231. public function testAddPadding() {
  232. $result = self::invokePrivate($this->crypt, 'addPadding', array('data'));
  233. $this->assertSame('dataxxx', $result);
  234. }
  235. /**
  236. * test removePadding()
  237. *
  238. * @dataProvider dataProviderRemovePadding
  239. * @param $data
  240. * @param $expected
  241. */
  242. public function testRemovePadding($data, $expected) {
  243. $result = self::invokePrivate($this->crypt, 'removePadding', array($data));
  244. $this->assertSame($expected, $result);
  245. }
  246. /**
  247. * data provider for testRemovePadding
  248. *
  249. * @return array
  250. */
  251. public function dataProviderRemovePadding() {
  252. return array(
  253. array('dataxx', 'data'),
  254. array('data', false)
  255. );
  256. }
  257. /**
  258. * test parseHeader()
  259. */
  260. public function testParseHeader() {
  261. $header= 'HBEGIN:foo:bar:cipher:AES-256-CFB:HEND';
  262. $result = self::invokePrivate($this->crypt, 'parseHeader', array($header));
  263. $this->assertTrue(is_array($result));
  264. $this->assertSame(2, count($result));
  265. $this->assertArrayHasKey('foo', $result);
  266. $this->assertArrayHasKey('cipher', $result);
  267. $this->assertSame('bar', $result['foo']);
  268. $this->assertSame('AES-256-CFB', $result['cipher']);
  269. }
  270. /**
  271. * test encrypt()
  272. *
  273. * @return string
  274. */
  275. public function testEncrypt() {
  276. $decrypted = 'content';
  277. $password = 'password';
  278. $iv = self::invokePrivate($this->crypt, 'generateIv');
  279. $this->assertTrue(is_string($iv));
  280. $this->assertSame(16, strlen($iv));
  281. $result = self::invokePrivate($this->crypt, 'encrypt', array($decrypted, $iv, $password));
  282. $this->assertTrue(is_string($result));
  283. return array(
  284. 'password' => $password,
  285. 'iv' => $iv,
  286. 'encrypted' => $result,
  287. 'decrypted' => $decrypted);
  288. }
  289. /**
  290. * test decrypt()
  291. *
  292. * @depends testEncrypt
  293. */
  294. public function testDecrypt($data) {
  295. $result = self::invokePrivate(
  296. $this->crypt,
  297. 'decrypt',
  298. array($data['encrypted'], $data['iv'], $data['password']));
  299. $this->assertSame($data['decrypted'], $result);
  300. }
  301. /**
  302. * test return values of valid ciphers
  303. *
  304. * @dataProvider dataTestGetKeySize
  305. */
  306. public function testGetKeySize($cipher, $expected) {
  307. $result = $this->invokePrivate($this->crypt, 'getKeySize', [$cipher]);
  308. $this->assertSame($expected, $result);
  309. }
  310. /**
  311. * test exception if cipher is unknown
  312. *
  313. * @expectedException \InvalidArgumentException
  314. */
  315. public function testGetKeySizeFailure() {
  316. $this->invokePrivate($this->crypt, 'getKeySize', ['foo']);
  317. }
  318. /**
  319. * @return array
  320. */
  321. public function dataTestGetKeySize() {
  322. return [
  323. ['AES-256-CFB', 32],
  324. ['AES-128-CFB', 16],
  325. ['AES-256-CTR', 32],
  326. ['AES-128-CTR', 16],
  327. ];
  328. }
  329. /**
  330. * @dataProvider dataTestDecryptPrivateKey
  331. */
  332. public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected) {
  333. /** @var \OCA\Encryption\Crypto\Crypt | \PHPUnit_Framework_MockObject_MockObject $crypt */
  334. $crypt = $this->getMockBuilder(Crypt::class)
  335. ->setConstructorArgs(
  336. [
  337. $this->logger,
  338. $this->userSession,
  339. $this->config,
  340. $this->l
  341. ]
  342. )
  343. ->setMethods(
  344. [
  345. 'parseHeader',
  346. 'generatePasswordHash',
  347. 'symmetricDecryptFileContent',
  348. 'isValidPrivateKey'
  349. ]
  350. )
  351. ->getMock();
  352. $crypt->expects($this->once())->method('parseHeader')->willReturn($header);
  353. if (isset($header['keyFormat']) && $header['keyFormat'] === 'hash') {
  354. $crypt->expects($this->once())->method('generatePasswordHash')->willReturn('hash');
  355. $password = 'hash';
  356. } else {
  357. $crypt->expects($this->never())->method('generatePasswordHash');
  358. $password = 'password';
  359. }
  360. $crypt->expects($this->once())->method('symmetricDecryptFileContent')
  361. ->with('privateKey', $password, $expectedCipher)->willReturn('key');
  362. $crypt->expects($this->once())->method('isValidPrivateKey')->willReturn($isValidKey);
  363. $result = $crypt->decryptPrivateKey($privateKey, 'password');
  364. $this->assertSame($expected, $result);
  365. }
  366. /**
  367. * @return array
  368. */
  369. public function dataTestDecryptPrivateKey() {
  370. return [
  371. [['cipher' => 'AES-128-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-128-CFB', true, 'key'],
  372. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  373. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', false, false],
  374. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'hash'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  375. [['cipher' => 'AES-256-CFB'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  376. [[], 'privateKey', 'AES-128-CFB', true, 'key'],
  377. ];
  378. }
  379. public function testIsValidPrivateKey() {
  380. $res = openssl_pkey_new();
  381. openssl_pkey_export($res, $privateKey);
  382. // valid private key
  383. $this->assertTrue(
  384. $this->invokePrivate($this->crypt, 'isValidPrivateKey', [$privateKey])
  385. );
  386. // invalid private key
  387. $this->assertFalse(
  388. $this->invokePrivate($this->crypt, 'isValidPrivateKey', ['foo'])
  389. );
  390. }
  391. }