aboutsummaryrefslogtreecommitdiff
path: root/cli/Commands/OAuth2/Keys.php
blob: 9132ad6152fa8c112e43a1f2218aaf0bee8a5d2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

namespace Studip\Cli\Commands\OAuth2;

use phpseclib3\Crypt\RSA;
use Studip\OAuth2\Container;
use Studip\OAuth2\KeyInformation;
use Studip\OAuth2\SetupInformation;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class Keys extends Command
{
    protected static $defaultName = 'oauth2:keys';

    protected function configure(): void
    {
        $this->setDescription(
            'Erstelle alle kryptografischen Schlüssel, um Stud.IP als OAuth2-Authorization-Server zu verwenden.'
        );
        $this->addOption('force', null, InputOption::VALUE_NONE, 'Überschreibe ggf. vorhandene Schlüssel');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $container = new Container();
        $setup = $container->get(SetupInformation::class);

        $encryptionKey = $setup->encryptionKey();
        $publicKey = $setup->publicKey();
        $privateKey = $setup->privateKey();

        $force = $input->getOption('force');

        if (($encryptionKey->exists() || $publicKey->exists() || $privateKey->exists()) && !$force) {
            $io->error(
                'Schlüsseldateien liegen bereits vor. Verwenden Sie die Option --force, um diese zu überschreiben.'
            );
            return Command::FAILURE;
        }

        $this->storeKeyContentsToFile($encryptionKey, $this->generateEncryptionKey());

        $key = RSA::createKey(4096);
        $this->storeKeyContentsToFile($publicKey, (string) $key->getPublicKey());
        $this->storeKeyContentsToFile($privateKey, (string) $key);

        $io->info('Schlüsseldateien erfolgreich angelegt.');

        return Command::SUCCESS;
    }

    private function storeKeyContentsToFile(KeyInformation $key, string $contents)
    {
        file_put_contents($key->filename(), $contents);
        chmod($key->filename(), 0660);
    }

    private function generateEncryptionKey(): string
    {
        return "<?php return '" . randomString(48) . "';";
    }
}