Verify.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Command\User\Keys;
  8. use OC\Security\IdentityProof\Manager;
  9. use OCP\IUser;
  10. use OCP\IUserManager;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Input\InputArgument;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Output\OutputInterface;
  15. class Verify extends Command {
  16. public function __construct(
  17. protected IUserManager $userManager,
  18. protected Manager $keyManager,
  19. ) {
  20. parent::__construct();
  21. }
  22. protected function configure(): void {
  23. $this
  24. ->setName('user:keys:verify')
  25. ->setDescription('Verify if the stored public key matches the stored private key')
  26. ->addArgument(
  27. 'user-id',
  28. InputArgument::REQUIRED,
  29. 'User ID of the user to verify'
  30. )
  31. ;
  32. }
  33. /**
  34. * @param InputInterface $input
  35. * @param OutputInterface $output
  36. * @return int
  37. */
  38. protected function execute(InputInterface $input, OutputInterface $output): int {
  39. $userId = $input->getArgument('user-id');
  40. $user = $this->userManager->get($userId);
  41. if (!$user instanceof IUser) {
  42. $output->writeln('Unknown user');
  43. return static::FAILURE;
  44. }
  45. $key = $this->keyManager->getKey($user);
  46. $publicKey = $key->getPublic();
  47. $privateKey = $key->getPrivate();
  48. $output->writeln('User public key size: ' . strlen($publicKey));
  49. $output->writeln('User private key size: ' . strlen($privateKey));
  50. // Derive the public key from the private key again to validate the stored public key
  51. $opensslPrivateKey = openssl_pkey_get_private($privateKey);
  52. $publicKeyDerived = openssl_pkey_get_details($opensslPrivateKey);
  53. $publicKeyDerived = $publicKeyDerived['key'];
  54. $output->writeln('User derived public key size: ' . strlen($publicKeyDerived));
  55. $output->writeln('');
  56. $output->writeln('Stored public key:');
  57. $output->writeln($publicKey);
  58. $output->writeln('Derived public key:');
  59. $output->writeln($publicKeyDerived);
  60. if ($publicKey != $publicKeyDerived) {
  61. $output->writeln('<error>Stored public key does not match stored private key</error>');
  62. return static::FAILURE;
  63. }
  64. $output->writeln('<info>Stored public key matches stored private key</info>');
  65. return static::SUCCESS;
  66. }
  67. }