UserPasswordEncoderCommand.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\SecurityBundle\Command;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Exception\InvalidArgumentException;
  13. use Symfony\Component\Console\Exception\RuntimeException;
  14. use Symfony\Component\Console\Input\InputArgument;
  15. use Symfony\Component\Console\Input\InputInterface;
  16. use Symfony\Component\Console\Input\InputOption;
  17. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  18. use Symfony\Component\Console\Output\OutputInterface;
  19. use Symfony\Component\Console\Question\Question;
  20. use Symfony\Component\Console\Style\SymfonyStyle;
  21. use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
  22. use Symfony\Component\Security\Core\Encoder\SelfSaltingEncoderInterface;
  23. /**
  24. * Encode a user's password.
  25. *
  26. * @author Sarah Khalil <mkhalil.sarah@gmail.com>
  27. *
  28. * @final
  29. */
  30. class UserPasswordEncoderCommand extends Command
  31. {
  32. protected static $defaultName = 'security:encode-password';
  33. private $encoderFactory;
  34. private $userClasses;
  35. public function __construct(EncoderFactoryInterface $encoderFactory, array $userClasses = [])
  36. {
  37. $this->encoderFactory = $encoderFactory;
  38. $this->userClasses = $userClasses;
  39. parent::__construct();
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function configure()
  45. {
  46. $this
  47. ->setDescription('Encode a password')
  48. ->addArgument('password', InputArgument::OPTIONAL, 'The plain password to encode.')
  49. ->addArgument('user-class', InputArgument::OPTIONAL, 'The User entity class path associated with the encoder used to encode the password.')
  50. ->addOption('empty-salt', null, InputOption::VALUE_NONE, 'Do not generate a salt or let the encoder generate one.')
  51. ->setHelp(<<<EOF
  52. The <info>%command.name%</info> command encodes passwords according to your
  53. security configuration. This command is mainly used to generate passwords for
  54. the <comment>in_memory</comment> user provider type and for changing passwords
  55. in the database while developing the application.
  56. Suppose that you have the following security configuration in your application:
  57. <comment>
  58. # app/config/security.yml
  59. security:
  60. encoders:
  61. Symfony\Component\Security\Core\User\User: plaintext
  62. App\Entity\User: auto
  63. </comment>
  64. If you execute the command non-interactively, the first available configured
  65. user class under the <comment>security.encoders</comment> key is used and a random salt is
  66. generated to encode the password:
  67. <info>php %command.full_name% --no-interaction [password]</info>
  68. Pass the full user class path as the second argument to encode passwords for
  69. your own entities:
  70. <info>php %command.full_name% --no-interaction [password] 'App\Entity\User'</info>
  71. Executing the command interactively allows you to generate a random salt for
  72. encoding the password:
  73. <info>php %command.full_name% [password] 'App\Entity\User'</info>
  74. In case your encoder doesn't require a salt, add the <comment>empty-salt</comment> option:
  75. <info>php %command.full_name% --empty-salt [password] 'App\Entity\User'</info>
  76. EOF
  77. )
  78. ;
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected function execute(InputInterface $input, OutputInterface $output): int
  84. {
  85. $io = new SymfonyStyle($input, $output);
  86. $errorIo = $output instanceof ConsoleOutputInterface ? new SymfonyStyle($input, $output->getErrorOutput()) : $io;
  87. $input->isInteractive() ? $errorIo->title('Symfony Password Encoder Utility') : $errorIo->newLine();
  88. $password = $input->getArgument('password');
  89. $userClass = $this->getUserClass($input, $io);
  90. $emptySalt = $input->getOption('empty-salt');
  91. $encoder = $this->encoderFactory->getEncoder($userClass);
  92. $saltlessWithoutEmptySalt = !$emptySalt && $encoder instanceof SelfSaltingEncoderInterface;
  93. if ($saltlessWithoutEmptySalt) {
  94. $emptySalt = true;
  95. }
  96. if (!$password) {
  97. if (!$input->isInteractive()) {
  98. $errorIo->error('The password must not be empty.');
  99. return 1;
  100. }
  101. $passwordQuestion = $this->createPasswordQuestion();
  102. $password = $errorIo->askQuestion($passwordQuestion);
  103. }
  104. $salt = null;
  105. if ($input->isInteractive() && !$emptySalt) {
  106. $emptySalt = true;
  107. $errorIo->note('The command will take care of generating a salt for you. Be aware that some encoders advise to let them generate their own salt. If you\'re using one of those encoders, please answer \'no\' to the question below. '.\PHP_EOL.'Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.');
  108. if ($errorIo->confirm('Confirm salt generation ?')) {
  109. $salt = $this->generateSalt();
  110. $emptySalt = false;
  111. }
  112. } elseif (!$emptySalt) {
  113. $salt = $this->generateSalt();
  114. }
  115. $encodedPassword = $encoder->encodePassword($password, $salt);
  116. $rows = [
  117. ['Encoder used', \get_class($encoder)],
  118. ['Encoded password', $encodedPassword],
  119. ];
  120. if (!$emptySalt) {
  121. $rows[] = ['Generated salt', $salt];
  122. }
  123. $io->table(['Key', 'Value'], $rows);
  124. if (!$emptySalt) {
  125. $errorIo->note(sprintf('Make sure that your salt storage field fits the salt length: %s chars', \strlen($salt)));
  126. } elseif ($saltlessWithoutEmptySalt) {
  127. $errorIo->note('Self-salting encoder used: the encoder generated its own built-in salt.');
  128. }
  129. $errorIo->success('Password encoding succeeded');
  130. return 0;
  131. }
  132. /**
  133. * Create the password question to ask the user for the password to be encoded.
  134. */
  135. private function createPasswordQuestion(): Question
  136. {
  137. $passwordQuestion = new Question('Type in your password to be encoded');
  138. return $passwordQuestion->setValidator(function ($value) {
  139. if ('' === trim($value)) {
  140. throw new InvalidArgumentException('The password must not be empty.');
  141. }
  142. return $value;
  143. })->setHidden(true)->setMaxAttempts(20);
  144. }
  145. private function generateSalt(): string
  146. {
  147. return base64_encode(random_bytes(30));
  148. }
  149. private function getUserClass(InputInterface $input, SymfonyStyle $io): string
  150. {
  151. if (null !== $userClass = $input->getArgument('user-class')) {
  152. return $userClass;
  153. }
  154. if (empty($this->userClasses)) {
  155. throw new RuntimeException('There are no configured encoders for the "security" extension.');
  156. }
  157. if (!$input->isInteractive() || 1 === \count($this->userClasses)) {
  158. return reset($this->userClasses);
  159. }
  160. $userClasses = $this->userClasses;
  161. natcasesort($userClasses);
  162. $userClasses = array_values($userClasses);
  163. return $io->choice('For which user class would you like to encode a password?', $userClasses, reset($userClasses));
  164. }
  165. }