-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathCfsslHandler.php
More file actions
625 lines (545 loc) · 17.2 KB
/
CfsslHandler.php
File metadata and controls
625 lines (545 loc) · 17.2 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Libresign\Handler\CertificateEngine;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use OC\SystemConfig;
use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\Db\CrlMapper;
use OCA\Libresign\Enum\CertificateType;
use OCA\Libresign\Exception\EmptyCertificateException;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\CfsslServerHandler;
use OCA\Libresign\Helper\ConfigureCheckHelper;
use OCA\Libresign\Service\CaIdentifierService;
use OCA\Libresign\Service\CertificatePolicyService;
use OCA\Libresign\Service\Install\InstallService;
use OCP\Files\AppData\IAppDataFactory;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IDateTimeFormatter;
use OCP\ITempManager;
use OCP\IURLGenerator;
use Psr\Log\LoggerInterface;
/**
* Class CfsslHandler
*
* @package OCA\Libresign\Handler
*
* @method CfsslHandler setClient(Client $client)
*/
class CfsslHandler extends AEngineHandler implements IEngineHandler {
public const CFSSL_URI = 'http://127.0.0.1:8888/api/v1/cfssl/';
/** @var Client */
protected $client;
protected $cfsslUri;
private string $binary = '';
public function __construct(
protected IConfig $config,
protected IAppConfig $appConfig,
private SystemConfig $systemConfig,
protected IAppDataFactory $appDataFactory,
protected IDateTimeFormatter $dateTimeFormatter,
protected ITempManager $tempManager,
protected CfsslServerHandler $cfsslServerHandler,
protected CertificatePolicyService $certificatePolicyService,
protected IURLGenerator $urlGenerator,
protected CaIdentifierService $caIdentifierService,
protected CrlMapper $crlMapper,
protected LoggerInterface $logger,
) {
parent::__construct(
$config,
$appConfig,
$appDataFactory,
$dateTimeFormatter,
$tempManager,
$certificatePolicyService,
$urlGenerator,
$caIdentifierService,
$logger,
);
$this->cfsslServerHandler->configCallback(fn () => $this->getCurrentConfigPath());
}
public function generateRootCert(
string $commonName,
array $names = [],
): void {
if (empty($commonName)) {
throw new EmptyCertificateException('Common Name (CN) cannot be empty for root certificate');
}
$this->cfsslServerHandler->createConfigServer(
$commonName,
$names,
$this->getCaExpiryInDays(),
$this->getCrlDistributionUrl(),
);
$this->gencert();
$this->stopIfRunning();
for ($i = 1; $i <= 4; $i++) {
if ($this->isUp()) {
break;
}
sleep(2);
}
}
public function generateCertificate(): string {
$this->validateRootCertificate();
$certKeys = $this->newCert();
$pkcs12 = parent::exportToPkcs12(
$certKeys['certificate'],
$certKeys['private_key'],
[
'friendly_name' => $this->getFriendlyName(),
'extracerts' => [
$certKeys['certificate'],
$certKeys['certificate_request'],
],
],
);
$parsed = $this->readCertificate($pkcs12, $this->getPassword());
$this->persistSerialNumberToCrl($parsed);
return $pkcs12;
}
public function isSetupOk(): bool {
$configPath = $this->getCurrentConfigPath();
$certificate = file_exists($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
$privateKey = file_exists($configPath . DIRECTORY_SEPARATOR . 'ca-key.pem');
if (!$certificate || !$privateKey) {
return false;
}
try {
$this->getClient();
return true;
} catch (\Throwable) {
}
return false;
}
protected function getConfigureCheckResourceName(): string {
return 'cfssl-configure';
}
protected function getCertificateRegenerationTip(): string {
return 'Consider regenerating the root certificate with: occ libresign:configure:cfssl --cn="Your CA Name"';
}
protected function getEngineSpecificChecks(): array {
return $this->checkBinaries();
}
protected function getSetupSuccessMessage(): string {
return 'Root certificate config files found.';
}
protected function getSetupErrorMessage(): string {
return 'CFSSL (root certificate) not configured.';
}
protected function getSetupErrorTip(): string {
return 'Run occ libresign:configure:cfssl --help';
}
public function toArray(): array {
$return = parent::toArray();
if (!empty($return['configPath'])) {
$return['cfsslUri'] = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_uri');
}
return $return;
}
public function getCommonName(): string {
$uid = $this->getUID();
if (!$uid) {
return $this->commonName;
}
return $uid . ', ' . $this->commonName;
}
private function newCert(): array {
$json = [
'json' => [
'profile' => 'client',
'request' => [
'hosts' => $this->getHosts(),
'CN' => $this->getCommonName(),
'key' => [
'algo' => 'rsa',
'size' => 2048,
],
'names' => [],
'crl_url' => $this->getCrlDistributionUrl(),
],
],
];
$names = $this->getNames();
foreach ($names as $key => $value) {
if (!empty($value) && is_array($value)) {
$names[$key] = implode(', ', $value);
}
}
if (!empty($names)) {
$json['json']['request']['names'][] = $names;
}
try {
$response = $this->getClient()
->request('post',
'newcert',
$json
)
;
} catch (RequestException|ConnectException $th) {
if ($th->getHandlerContext() && $th->getHandlerContext()['error']) {
throw new \Exception($th->getHandlerContext()['error'], 1);
}
throw new LibresignException($th->getMessage(), 500);
}
$responseDecoded = json_decode((string)$response->getBody(), true);
if (!isset($responseDecoded['success']) || !$responseDecoded['success']) {
throw new LibresignException('Error while generating certificate keys!', 500);
}
return $responseDecoded['result'];
}
private function gencert(): void {
$binary = $this->getBinary();
$configPath = $this->getCurrentConfigPath();
$csrFile = $configPath . '/csr_server.json';
$cmd = escapeshellcmd($binary) . ' gencert -initca ' . escapeshellarg($csrFile);
$output = shell_exec($cmd);
if (!$output) {
throw new \RuntimeException('cfssl without output.');
}
$json = json_decode($output, true);
if (!$json || !isset($json['cert'], $json['key'], $json['csr'])) {
throw new \RuntimeException('Error generating CA: invalid cfssl output.');
}
file_put_contents($configPath . '/ca.pem', $json['cert']);
file_put_contents($configPath . '/ca-key.pem', $json['key']);
file_put_contents($configPath . '/ca.csr', $json['csr']);
$this->persistRootCertificateFromData($json['cert']);
}
private function getClient(): Client {
if (!$this->client) {
$this->setClient(new Client(['base_uri' => $this->getCfsslUri()]));
}
$this->wakeUp();
return $this->client;
}
private function isUp(): bool {
try {
$client = $this->getClient();
if (!$this->portOpen()) {
throw new LibresignException('CFSSL server is down', 500);
}
$response = $client
->request('get',
'health',
[
'base_uri' => $this->getCfsslUri()
]
)
;
} catch (RequestException|ConnectException $th) {
switch ($th->getCode()) {
case 404:
throw new \Exception('Endpoint /health of CFSSL server not found. Maybe you are using incompatible version of CFSSL server. Use latests version.', 1);
default:
if ($th->getHandlerContext() && $th->getHandlerContext()['error']) {
throw new \Exception($th->getHandlerContext()['error'], 1);
}
throw new LibresignException($th->getMessage(), 500);
}
}
$responseDecoded = json_decode((string)$response->getBody(), true);
if (!isset($responseDecoded['success']) || !$responseDecoded['success']) {
throw new LibresignException('Error while check cfssl API health!', 500);
}
if (empty($responseDecoded['result']) || empty($responseDecoded['result']['healthy'])) {
return false;
}
return (bool)$responseDecoded['result']['healthy'];
}
private function wakeUp(): void {
if ($this->portOpen()) {
return;
}
$binary = $this->getBinary();
$configPath = $this->getCurrentConfigPath();
if (!$configPath) {
throw new LibresignException('CFSSL not configured.');
}
$this->cfsslServerHandler->updateExpirity($this->getCaExpiryInDays());
$cmd = 'nohup ' . $binary . ' serve -address=127.0.0.1 '
. '-ca-key ' . $configPath . DIRECTORY_SEPARATOR . 'ca-key.pem '
. '-ca ' . $configPath . DIRECTORY_SEPARATOR . 'ca.pem '
. '-config ' . $configPath . DIRECTORY_SEPARATOR . 'config_server.json > /dev/null 2>&1 & echo $!';
shell_exec($cmd);
$loops = 0;
while (!$this->portOpen() && $loops <= 4) {
sleep(1);
$loops++;
}
}
private function portOpen(): bool {
$host = parse_url($this->getCfsslUri(), PHP_URL_HOST);
$port = parse_url($this->getCfsslUri(), PHP_URL_PORT);
set_error_handler(function (): void { });
$socket = fsockopen($host, $port, $errno, $errstr, 0.1);
restore_error_handler();
if (!$socket || $errno || $errstr) {
return false;
}
fclose($socket);
return true;
}
private function getServerPid(): int {
$cmd = 'ps -eo pid,command|';
$cmd .= 'grep "cfssl.*serve.*-address"|'
. 'grep -v grep|'
. 'grep -v defunct|'
. 'sed -e "s/^[[:space:]]*//"|cut -d" " -f1';
$output = shell_exec($cmd);
if (!is_string($output)) {
return 0;
}
$pid = trim($output);
return (int)$pid;
}
/**
* Parse command
*
* Have commands that need to be executed as sudo otherwise don't will work,
* by example the command runuser or kill. To prevent error when run in a
* GitHub Actions, these commands are executed prefixed by sudo when exists
* an environment called GITHUB_ACTIONS.
*/
private function parseCommand(string $command): string {
if (getenv('GITHUB_ACTIONS') !== false) {
$command = 'sudo ' . $command;
}
return $command;
}
private function stopIfRunning(): void {
$pid = $this->getServerPid();
if ($pid > 0) {
exec($this->parseCommand('kill -9 ' . $pid));
}
}
private function getBinary(): string {
if ($this->binary) {
return $this->binary;
}
if (PHP_OS_FAMILY === 'Windows') {
throw new LibresignException('Incompatible with Windows');
}
if ($this->appConfig->hasKey(Application::APP_ID, 'cfssl_bin')) {
$binary = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_bin');
if (!file_exists($binary)) {
$this->appConfig->deleteKey(Application::APP_ID, 'cfssl_bin');
}
return $binary;
}
throw new LibresignException('Binary of CFSSL not found. Install binaries.');
}
private function getCfsslUri(): string {
if ($this->cfsslUri) {
return $this->cfsslUri;
}
if ($uri = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_uri')) {
return $uri;
}
$this->appConfig->deleteKey(Application::APP_ID, 'cfssl_uri');
$this->cfsslUri = self::CFSSL_URI;
return $this->cfsslUri;
}
public function setCfsslUri($uri): void {
if ($uri) {
$this->appConfig->setValueString(Application::APP_ID, 'cfssl_uri', $uri);
} else {
$this->appConfig->deleteKey(Application::APP_ID, 'cfssl_uri');
}
$this->cfsslUri = $uri;
}
private function checkBinaries(): array {
if (PHP_OS_FAMILY === 'Windows') {
return [
(new ConfigureCheckHelper())
->setErrorMessage('CFSSL is incompatible with Windows')
->setResource('cfssl'),
];
}
$binary = $this->appConfig->getValueString(Application::APP_ID, 'cfssl_bin');
if (!$binary) {
return [
(new ConfigureCheckHelper())
->setErrorMessage('CFSSL not installed.')
->setResource('cfssl')
->setTip('Run occ libresign:install --cfssl'),
];
}
if (!file_exists($binary)) {
return [
(new ConfigureCheckHelper())
->setErrorMessage('CFSSL not found.')
->setResource('cfssl')
->setTip('Run occ libresign:install --cfssl'),
];
}
$version = shell_exec("$binary version");
if (!is_string($version) || empty($version)) {
return [
(new ConfigureCheckHelper())
->setErrorMessage(sprintf(
'Failed to run the command "%s" with user %s',
"$binary version",
get_current_user()
))
->setResource('cfssl')
->setTip('Run occ libresign:install --cfssl')
];
}
preg_match_all('/: (?<version>.*)/', $version, $matches);
if (!$matches || !isset($matches['version']) || count($matches['version']) !== 2) {
return [
(new ConfigureCheckHelper())
->setErrorMessage(sprintf(
'Failed to identify cfssl version with command %s',
"$binary version"
))
->setResource('cfssl')
->setTip('Run occ libresign:install --cfssl')
];
}
if (!str_contains($matches['version'][0], InstallService::CFSSL_VERSION)) {
return [
(new ConfigureCheckHelper())
->setErrorMessage(sprintf(
'Invalid version. Expected: %s, actual: %s',
InstallService::CFSSL_VERSION,
$matches['version'][0]
))
->setResource('cfssl')
->setTip('Run occ libresign:install --cfssl')
];
}
$return = [];
$return[] = (new ConfigureCheckHelper())
->setSuccessMessage('CFSSL binary path: ' . $binary)
->setResource('cfssl');
$return[] = (new ConfigureCheckHelper())
->setSuccessMessage('CFSSL version: ' . $matches['version'][0])
->setResource('cfssl');
$return[] = (new ConfigureCheckHelper())
->setSuccessMessage('Runtime: ' . $matches['version'][1])
->setResource('cfssl');
return $return;
}
/**
* Get Authority Key Identifier from certificate (needed for CFSSL revocation)
*
* @param string $certificatePem PEM encoded certificate
* @return string Authority Key Identifier in lowercase without colons
*/
public function getAuthorityKeyId(string $certificatePem): string {
$cert = openssl_x509_read($certificatePem);
if (!$cert) {
throw new \RuntimeException('Invalid certificate format');
}
$parsed = openssl_x509_parse($cert);
if (!$parsed || !isset($parsed['extensions']['authorityKeyIdentifier'])) {
throw new \RuntimeException('Certificate does not contain Authority Key Identifier');
}
$authKeyId = $parsed['extensions']['authorityKeyIdentifier'];
if (preg_match('/keyid:([A-Fa-f0-9:]+)/', $authKeyId, $matches)) {
return strtolower(str_replace(':', '', $matches[1]));
}
throw new \RuntimeException('Could not parse Authority Key Identifier');
}
/**
* Revoke a certificate using CFSSL API
*
* @param string $serialNumber Certificate serial number in decimal format
* @param string $authorityKeyId Authority key identifier (lowercase, no colons)
* @param string $reason CRLReason description string (e.g., 'superseded', 'keyCompromise')
*/
public function revokeCertificate(string $serialNumber, string $authorityKeyId, string $reason): bool {
try {
$json = [
'json' => [
'serial' => $serialNumber,
'authority_key_id' => $authorityKeyId,
'reason' => $reason,
],
];
$response = $this->getClient()->request('POST', 'revoke', $json);
$responseData = json_decode((string)$response->getBody(), true);
if (!isset($responseData['success'])) {
$errorMessage = isset($responseData['errors'])
? implode(', ', array_column($responseData['errors'], 'message'))
: 'Unknown CFSSL error';
throw new \RuntimeException('CFSSL revocation failed: ' . $errorMessage);
}
return $responseData['success'];
} catch (RequestException|ConnectException $e) {
throw new \RuntimeException('Failed to communicate with CFSSL server: ' . $e->getMessage());
} catch (\Throwable $e) {
throw new \RuntimeException('CFSSL certificate revocation error: ' . $e->getMessage());
}
}
private function persistSerialNumberToCrl(array $parsed): void {
if (!isset($parsed['serialNumberHex']) || !isset($parsed['valid_to'])) {
return;
}
$serialNumber = $parsed['serialNumberHex'];
$owner = $this->getCommonName() ?? 'Unknown';
$expiresAt = null;
if (isset($parsed['validTo_time_t'])) {
$expiresAt = new \DateTime('@' . $parsed['validTo_time_t']);
}
$issuer = $parsed['issuer'] ?? [];
$subject = $parsed['subject'] ?? [];
$this->crlMapper->createCertificate(
$serialNumber,
$owner,
'cfssl',
$this->caIdentifierService->getInstanceId(),
$this->caIdentifierService->getCaIdParsed()['generation'],
new \DateTime(),
$expiresAt,
$issuer,
$subject,
CertificateType::LEAF->value,
);
}
private function persistRootCertificateFromData(string $certPem): void {
$x509Resource = openssl_x509_read($certPem);
if (!$x509Resource) {
throw new \RuntimeException('Failed to parse root certificate');
}
$parsed = openssl_x509_parse($x509Resource);
if (!$parsed) {
throw new \RuntimeException('Failed to extract root certificate information');
}
$serialNumber = $parsed['serialNumberHex'] ?? '';
if (empty($serialNumber)) {
throw new \RuntimeException('Root certificate has no serial number');
}
$owner = $this->getCommonName() ?? 'Root CA';
$expiresAt = null;
if (isset($parsed['validTo_time_t'])) {
$expiresAt = new \DateTime('@' . $parsed['validTo_time_t']);
}
/** @var array<string, mixed> $issuer */
$issuer = $parsed['issuer'] ?? [];
/** @var array<string, mixed> $subject */
$subject = $parsed['subject'] ?? [];
$this->crlMapper->createCertificate(
$serialNumber,
$owner,
'cfssl',
$this->caIdentifierService->getInstanceId(),
$this->caIdentifierService->getCaIdParsed()['generation'],
new \DateTime(),
$expiresAt,
$issuer,
$subject,
CertificateType::ROOT->value,
);
}
}