summaryrefslogtreecommitdiffstats
path: root/application/clicommands/ImportCommand.php
blob: 2e7b15788ebd1b38e2b1099b606d7bfca0f9c7e7 (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
<?php

// Icinga Web 2 X.509 Module | (c) 2018 Icinga GmbH | GPLv2

namespace Icinga\Module\X509\Clicommands;

use Icinga\Application\Logger;
use Icinga\Module\X509\CertificateUtils;
use Icinga\Module\X509\Command;
use Icinga\Module\X509\Common\Database;
use ipl\Sql\Connection;
use ipl\Sql\Expression;

class ImportCommand extends Command
{
    /**
     * Import all X.509 certificates from the given file and mark them as trusted
     *
     * USAGE:
     *
     *   icingacli x509 import --file <file>
     *
     * EXAMPLES:
     *
     *   icingacli x509 import --file /etc/ssl/certs/ca-bundle.crt
     */
    public function indexAction()
    {
        $file = $this->params->getRequired('file');

        if (! file_exists($file)) {
            Logger::warning('The specified certificate file does not exist.');
            exit(1);
        }

        $bundle = CertificateUtils::parseBundle($file);

        $count = 0;

        Database::get()->transaction(function (Connection $db) use ($bundle, &$count) {
            foreach ($bundle as $data) {
                $cert = openssl_x509_read($data);

                list($id, $_) = CertificateUtils::findOrInsertCert($db, $cert);

                $db->update(
                    'x509_certificate',
                    [
                        'trusted' => 'y',
                        'mtime'   => new Expression('UNIX_TIMESTAMP() * 1000')
                    ],
                    ['id = ?' => $id]
                );

                $count++;
            }
        });

        printf("Processed %d X.509 certificate%s.\n", $count, $count !== 1 ? 's' : '');
    }
}