CryptTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 Psr\Log\LoggerInterface;
  32. use OCP\IUserSession;
  33. use Test\TestCase;
  34. class CryptTest extends TestCase {
  35. /** @var LoggerInterface|\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(LoggerInterface::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('getSystemValueString')
  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:encoding:binary:HEND'],
  121. ['password', 'HBEGIN:cipher:AES-128-CFB:keyFormat:password:encoding:binary:HEND'],
  122. ['hash', 'HBEGIN:cipher:AES-128-CFB:keyFormat:hash:encoding:binary:HEND']
  123. ];
  124. }
  125. public function testGetCipherWithInvalidCipher() {
  126. $this->config->expects($this->once())
  127. ->method('getSystemValueString')
  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('getSystemValueString')
  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('getSystemValueBool')
  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('getSystemValueBool')
  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:encoding:binary:HEND';
  268. $result = self::invokePrivate($this->crypt, 'parseHeader', [$header]);
  269. $this->assertTrue(is_array($result));
  270. $this->assertSame(3, count($result));
  271. $this->assertArrayHasKey('foo', $result);
  272. $this->assertArrayHasKey('cipher', $result);
  273. $this->assertArrayHasKey('encoding', $result);
  274. $this->assertSame('bar', $result['foo']);
  275. $this->assertSame('AES-256-CFB', $result['cipher']);
  276. $this->assertSame('binary', $result['encoding']);
  277. }
  278. /**
  279. * test encrypt()
  280. *
  281. * @return string
  282. */
  283. public function testEncrypt() {
  284. $decrypted = 'content';
  285. $password = 'password';
  286. $cipher = 'AES-256-CTR';
  287. $iv = self::invokePrivate($this->crypt, 'generateIv');
  288. $this->assertTrue(is_string($iv));
  289. $this->assertSame(16, strlen($iv));
  290. $result = self::invokePrivate($this->crypt, 'encrypt', [$decrypted, $iv, $password, $cipher]);
  291. $this->assertTrue(is_string($result));
  292. return [
  293. 'password' => $password,
  294. 'iv' => $iv,
  295. 'cipher' => $cipher,
  296. 'encrypted' => $result,
  297. 'decrypted' => $decrypted];
  298. }
  299. /**
  300. * test decrypt()
  301. *
  302. * @depends testEncrypt
  303. */
  304. public function testDecrypt($data) {
  305. $result = self::invokePrivate(
  306. $this->crypt,
  307. 'decrypt',
  308. [$data['encrypted'], $data['iv'], $data['password'], $data['cipher'], true]);
  309. $this->assertSame($data['decrypted'], $result);
  310. }
  311. /**
  312. * test return values of valid ciphers
  313. *
  314. * @dataProvider dataTestGetKeySize
  315. */
  316. public function testGetKeySize($cipher, $expected) {
  317. $result = $this->invokePrivate($this->crypt, 'getKeySize', [$cipher]);
  318. $this->assertSame($expected, $result);
  319. }
  320. /**
  321. * test exception if cipher is unknown
  322. *
  323. */
  324. public function testGetKeySizeFailure() {
  325. $this->expectException(\InvalidArgumentException::class);
  326. $this->invokePrivate($this->crypt, 'getKeySize', ['foo']);
  327. }
  328. /**
  329. * @return array
  330. */
  331. public function dataTestGetKeySize() {
  332. return [
  333. ['AES-256-CFB', 32],
  334. ['AES-128-CFB', 16],
  335. ['AES-256-CTR', 32],
  336. ['AES-128-CTR', 16],
  337. ];
  338. }
  339. /**
  340. * @dataProvider dataTestDecryptPrivateKey
  341. */
  342. public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected) {
  343. $this->config->method('getSystemValueBool')
  344. ->withConsecutive(['encryption.legacy_format_support', false],
  345. ['encryption.use_legacy_base64_encoding', false])
  346. ->willReturnOnConsecutiveCalls(true, false);
  347. /** @var \OCA\Encryption\Crypto\Crypt | \PHPUnit\Framework\MockObject\MockObject $crypt */
  348. $crypt = $this->getMockBuilder(Crypt::class)
  349. ->setConstructorArgs(
  350. [
  351. $this->logger,
  352. $this->userSession,
  353. $this->config,
  354. $this->l
  355. ]
  356. )
  357. ->setMethods(
  358. [
  359. 'parseHeader',
  360. 'generatePasswordHash',
  361. 'symmetricDecryptFileContent',
  362. 'isValidPrivateKey'
  363. ]
  364. )
  365. ->getMock();
  366. $crypt->expects($this->once())->method('parseHeader')->willReturn($header);
  367. if (isset($header['keyFormat']) && $header['keyFormat'] === 'hash') {
  368. $crypt->expects($this->once())->method('generatePasswordHash')->willReturn('hash');
  369. $password = 'hash';
  370. } else {
  371. $crypt->expects($this->never())->method('generatePasswordHash');
  372. $password = 'password';
  373. }
  374. $crypt->expects($this->once())->method('symmetricDecryptFileContent')
  375. ->with('privateKey', $password, $expectedCipher)->willReturn('key');
  376. $crypt->expects($this->once())->method('isValidPrivateKey')->willReturn($isValidKey);
  377. $result = $crypt->decryptPrivateKey($privateKey, 'password');
  378. $this->assertSame($expected, $result);
  379. }
  380. /**
  381. * @return array
  382. */
  383. public function dataTestDecryptPrivateKey() {
  384. return [
  385. [['cipher' => 'AES-128-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-128-CFB', true, 'key'],
  386. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  387. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', false, false],
  388. [['cipher' => 'AES-256-CFB', 'keyFormat' => 'hash'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  389. [['cipher' => 'AES-256-CFB'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'],
  390. [[], 'privateKey', 'AES-128-CFB', true, 'key'],
  391. ];
  392. }
  393. public function testIsValidPrivateKey() {
  394. $res = openssl_pkey_new();
  395. openssl_pkey_export($res, $privateKey);
  396. // valid private key
  397. $this->assertTrue(
  398. $this->invokePrivate($this->crypt, 'isValidPrivateKey', [$privateKey])
  399. );
  400. // invalid private key
  401. $this->assertFalse(
  402. $this->invokePrivate($this->crypt, 'isValidPrivateKey', ['foo'])
  403. );
  404. }
  405. public function testMultiKeyEncrypt() {
  406. $res = openssl_pkey_new();
  407. openssl_pkey_export($res, $privateKey);
  408. $publicKeyPem = openssl_pkey_get_details($res)['key'];
  409. $publicKey = openssl_pkey_get_public($publicKeyPem);
  410. $shareKeys = $this->crypt->multiKeyEncrypt('content', ['user1' => $publicKey]);
  411. $this->assertEquals(
  412. 'content',
  413. $this->crypt->multiKeyDecrypt($shareKeys['user1'], $privateKey)
  414. );
  415. }
  416. }