CryptTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Björn Schießle <bjoern@schiessle.org>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  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. protected function setUp(): void {
  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([]);
  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(['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. */
  111. public function testGenerateHeaderInvalid() {
  112. $this->expectException(\InvalidArgumentException::class);
  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:hash2: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 [
  157. ['AES-128-CFB', 'AES-128-CFB'],
  158. ['AES-256-CFB', 'AES-256-CFB'],
  159. ['AES-128-CTR', 'AES-128-CTR'],
  160. ['AES-256-CTR', 'AES-256-CTR'],
  161. ['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. ['content', 'my_iv']);
  172. $this->assertSame('content00iv00my_iv',
  173. $result
  174. );
  175. }
  176. /**
  177. * @dataProvider dataTestSplitMetaData
  178. */
  179. public function testSplitMetaData($data, $expected) {
  180. $this->config->method('getSystemValue')
  181. ->with('encryption_skip_signature_check', false)
  182. ->willReturn(true);
  183. $result = self::invokePrivate($this->crypt, 'splitMetaData', [$data, 'AES-256-CFB']);
  184. $this->assertTrue(is_array($result));
  185. $this->assertSame(3, count($result));
  186. $this->assertArrayHasKey('encrypted', $result);
  187. $this->assertArrayHasKey('iv', $result);
  188. $this->assertArrayHasKey('signature', $result);
  189. $this->assertSame($expected['encrypted'], $result['encrypted']);
  190. $this->assertSame($expected['iv'], $result['iv']);
  191. $this->assertSame($expected['signature'], $result['signature']);
  192. }
  193. public function dataTestSplitMetaData() {
  194. return [
  195. ['encryptedContent00iv001234567890123456xx',
  196. ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => false]],
  197. ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx',
  198. ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => 'e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86']],
  199. ];
  200. }
  201. /**
  202. * @dataProvider dataTestHasSignature
  203. */
  204. public function testHasSignature($data, $expected) {
  205. $this->config->method('getSystemValue')
  206. ->with('encryption_skip_signature_check', false)
  207. ->willReturn(true);
  208. $this->assertSame($expected,
  209. $this->invokePrivate($this->crypt, 'hasSignature', [$data, 'AES-256-CFB'])
  210. );
  211. }
  212. public function dataTestHasSignature() {
  213. return [
  214. ['encryptedContent00iv001234567890123456xx', false],
  215. ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx', true]
  216. ];
  217. }
  218. /**
  219. * @dataProvider dataTestHasSignatureFail
  220. */
  221. public function testHasSignatureFail($cipher) {
  222. $this->expectException(\OCP\Encryption\Exceptions\GenericEncryptionException::class);
  223. $data = 'encryptedContent00iv001234567890123456xx';
  224. $this->invokePrivate($this->crypt, 'hasSignature', [$data, $cipher]);
  225. }
  226. public function dataTestHasSignatureFail() {
  227. return [
  228. ['AES-256-CTR'],
  229. ['aes-256-ctr'],
  230. ['AES-128-CTR'],
  231. ['ctr-256-ctr']
  232. ];
  233. }
  234. /**
  235. * test addPadding()
  236. */
  237. public function testAddPadding() {
  238. $result = self::invokePrivate($this->crypt, 'addPadding', ['data']);
  239. $this->assertSame('dataxxx', $result);
  240. }
  241. /**
  242. * test removePadding()
  243. *
  244. * @dataProvider dataProviderRemovePadding
  245. * @param $data
  246. * @param $expected
  247. */
  248. public function testRemovePadding($data, $expected) {
  249. $result = self::invokePrivate($this->crypt, 'removePadding', [$data]);
  250. $this->assertSame($expected, $result);
  251. }
  252. /**
  253. * data provider for testRemovePadding
  254. *
  255. * @return array
  256. */
  257. public function dataProviderRemovePadding() {
  258. return [
  259. ['dataxx', 'data'],
  260. ['data', false]
  261. ];
  262. }
  263. /**
  264. * test parseHeader()
  265. */
  266. public function testParseHeader() {
  267. $header= 'HBEGIN:foo:bar:cipher:AES-256-CFB:HEND';
  268. $result = self::invokePrivate($this->crypt, 'parseHeader', [$header]);
  269. $this->assertTrue(is_array($result));
  270. $this->assertSame(2, count($result));
  271. $this->assertArrayHasKey('foo', $result);
  272. $this->assertArrayHasKey('cipher', $result);
  273. $this->assertSame('bar', $result['foo']);
  274. $this->assertSame('AES-256-CFB', $result['cipher']);
  275. }
  276. /**
  277. * test encrypt()
  278. *
  279. * @return string
  280. */
  281. public function testEncrypt() {
  282. $decrypted = 'content';
  283. $password = 'password';
  284. $iv = self::invokePrivate($this->crypt, 'generateIv');
  285. $this->assertTrue(is_string($iv));
  286. $this->assertSame(16, strlen($iv));
  287. $result = self::invokePrivate($this->crypt, 'encrypt', [$decrypted, $iv, $password]);
  288. $this->assertTrue(is_string($result));
  289. return [
  290. 'password' => $password,
  291. 'iv' => $iv,
  292. 'encrypted' => $result,
  293. 'decrypted' => $decrypted];
  294. }
  295. /**
  296. * test decrypt()
  297. *
  298. * @depends testEncrypt
  299. */
  300. public function testDecrypt($data) {
  301. $result = self::invokePrivate(
  302. $this->crypt,
  303. 'decrypt',
  304. [$data['encrypted'], $data['iv'], $data['password']]);
  305. $this->assertSame($data['decrypted'], $result);
  306. }
  307. /**
  308. * test return values of valid ciphers
  309. *
  310. * @dataProvider dataTestGetKeySize
  311. */
  312. public function testGetKeySize($cipher, $expected) {
  313. $result = $this->invokePrivate($this->crypt, 'getKeySize', [$cipher]);
  314. $this->assertSame($expected, $result);
  315. }
  316. /**
  317. * test exception if cipher is unknown
  318. *
  319. */
  320. public function testGetKeySizeFailure() {
  321. $this->expectException(\InvalidArgumentException::class);
  322. $this->invokePrivate($this->crypt, 'getKeySize', ['foo']);
  323. }
  324. /**
  325. * @return array
  326. */
  327. public function dataTestGetKeySize() {
  328. return [
  329. ['AES-256-CFB', 32],
  330. ['AES-128-CFB', 16],
  331. ['AES-256-CTR', 32],
  332. ['AES-128-CTR', 16],
  333. ];
  334. }
  335. /**
  336. * @dataProvider dataTestDecryptPrivateKey
  337. */
  338. public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected) {
  339. $this->config->method('getSystemValueBool')
  340. ->with('encryption.legacy_format_support', false)
  341. ->willReturn(true);
  342. /** @var \OCA\Encryption\Crypto\Crypt | \PHPUnit\Framework\MockObject\MockObject $crypt */
  343. $crypt = $this->getMockBuilder(Crypt::class)
  344. ->setConstructorArgs(
  345. [
  346. $this->logger,
  347. $this->userSession,
  348. $this->config,
  349. $this->l
  350. ]
  351. )
  352. ->setMethods(
  353. [
  354. 'parseHeader',
  355. 'generatePasswordHash',
  356. 'symmetricDecryptFileContent',
  357. 'isValidPrivateKey'
  358. ]
  359. )
  360. ->getMock();
  361. $crypt->expects($this->once())->method('parseHeader')->willReturn($header);
  362. if (isset($header['keyFormat']) && $header['keyFormat'] === 'hash') {
  363. $crypt->expects($this->once())->method('generatePasswordHash')->willReturn('hash');
  364. $password = 'hash';
  365. } else {
  366. $crypt->expects($this->never())->method('generatePasswordHash');
  367. $password = 'password';
  368. }
  369. $crypt->expects($this->once())->method('symmetricDecryptFileContent')
  370. ->with('privateKey', $password, $expectedCipher)->willReturn('key');
  371. $crypt->expects($this->once())->method('isValidPrivateKey')->willReturn($isValidKey);
  372. $result = $crypt->decryptPrivateKey($privateKey, 'password');
  373. $this->assertSame($expected, $result);
  374. }
  375. /**
  376. * @return array
  377. */
  378. public function dataTestDecryptPrivateKey() {
  379. return [
  380. [['cipher' => 'AES-128-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-128-CFB', true, 'key'],
  381. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  382. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', false, false],
  383. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'hash'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  384. [['cipher' => 'AES-256-CFB'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  385. [[], 'privateKey', 'AES-128-CFB', true, 'key'],
  386. ];
  387. }
  388. public function testIsValidPrivateKey() {
  389. $res = openssl_pkey_new();
  390. openssl_pkey_export($res, $privateKey);
  391. // valid private key
  392. $this->assertTrue(
  393. $this->invokePrivate($this->crypt, 'isValidPrivateKey', [$privateKey])
  394. );
  395. // invalid private key
  396. $this->assertFalse(
  397. $this->invokePrivate($this->crypt, 'isValidPrivateKey', ['foo'])
  398. );
  399. }
  400. }