forked from acmephp/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AcmeClient.php
404 lines (341 loc) · 15.2 KB
/
AcmeClient.php
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
<?php
/*
* This file is part of the Acme PHP project.
*
* (c) Titouan Galopin <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AcmePhp\Core;
use AcmePhp\Core\Exception\AcmeCoreClientException;
use AcmePhp\Core\Exception\AcmeCoreServerException;
use AcmePhp\Core\Exception\Protocol\CertificateRequestFailedException;
use AcmePhp\Core\Exception\Protocol\CertificateRevocationException;
use AcmePhp\Core\Exception\Protocol\ChallengeFailedException;
use AcmePhp\Core\Exception\Protocol\ChallengeNotSupportedException;
use AcmePhp\Core\Exception\Protocol\ChallengeTimedOutException;
use AcmePhp\Core\Http\SecureHttpClient;
use AcmePhp\Core\Protocol\AuthorizationChallenge;
use AcmePhp\Core\Protocol\CertificateOrder;
use AcmePhp\Core\Protocol\ExternalAccount;
use AcmePhp\Core\Protocol\ResourcesDirectory;
use AcmePhp\Core\Protocol\RevocationReason;
use AcmePhp\Ssl\Certificate;
use AcmePhp\Ssl\CertificateRequest;
use AcmePhp\Ssl\CertificateResponse;
use AcmePhp\Ssl\Signer\CertificateRequestSigner;
use GuzzleHttp\Psr7\Utils;
use Webmozart\Assert\Assert;
/**
* ACME protocol client implementation.
*
* @author Titouan Galopin <[email protected]>
*/
class AcmeClient implements AcmeClientInterface
{
/**
* @var SecureHttpClient
*/
private $uninitializedHttpClient;
/**
* @var SecureHttpClient
*/
private $initializedHttpClient;
/**
* @var CertificateRequestSigner
*/
private $csrSigner;
/**
* @var string
*/
private $directoryUrl;
/**
* @var ResourcesDirectory
*/
private $directory;
/**
* @var string
*/
private $account;
public function __construct(SecureHttpClient $httpClient, string $directoryUrl, CertificateRequestSigner $csrSigner = null)
{
$this->uninitializedHttpClient = $httpClient;
$this->directoryUrl = $directoryUrl;
$this->csrSigner = $csrSigner ?: new CertificateRequestSigner();
}
/**
* {@inheritdoc}
*/
public function registerAccount(string $email = null, ExternalAccount $externalAccount = null): array
{
$client = $this->getHttpClient();
$payload = [
'termsOfServiceAgreed' => true,
'contact' => [],
];
if ($email) {
$payload['contact'][] = 'mailto:'.$email;
}
if ($externalAccount) {
$payload['externalAccountBinding'] = $client->createExternalAccountPayload(
$externalAccount,
$this->getResourceUrl(ResourcesDirectory::NEW_ACCOUNT)
);
}
$this->requestResource('POST', ResourcesDirectory::NEW_ACCOUNT, $payload);
$account = $this->getResourceAccount();
return $client->request('POST', $account, $client->signKidPayload($account, $account, null));
}
/**
* {@inheritdoc}
*/
public function requestOrder(array $domains): CertificateOrder
{
Assert::allStringNotEmpty($domains, 'requestOrder::$domains expected a list of strings. Got: %s');
$payload = [
'identifiers' => array_map(
static function ($domain) {
return [
'type' => 'dns',
'value' => $domain,
];
},
array_values($domains)
),
];
$client = $this->getHttpClient();
$resourceUrl = $this->getResourceUrl(ResourcesDirectory::NEW_ORDER);
$response = $client->request('POST', $resourceUrl, $client->signKidPayload($resourceUrl, $this->getResourceAccount(), $payload));
if (!isset($response['authorizations']) || !$response['authorizations']) {
throw new ChallengeNotSupportedException();
}
$authorizationsChallenges = [];
$orderEndpoint = $client->getLastLocation();
foreach ($response['authorizations'] as $authorizationEndpoint) {
$authorizationsResponse = $client->request('POST', $authorizationEndpoint, $client->signKidPayload($authorizationEndpoint, $this->getResourceAccount(), null));
$domain = (empty($authorizationsResponse['wildcard']) ? '' : '*.').$authorizationsResponse['identifier']['value'];
foreach ($authorizationsResponse['challenges'] as $challenge) {
$authorizationsChallenges[$domain][] = $this->createAuthorizationChallenge($authorizationsResponse['identifier']['value'], $challenge);
}
}
return new CertificateOrder($authorizationsChallenges, $orderEndpoint, $response['status']);
}
/**
* {@inheritdoc}
*/
public function reloadOrder(CertificateOrder $order): CertificateOrder
{
$client = $this->getHttpClient();
$orderEndpoint = $order->getOrderEndpoint();
$response = $client->request('POST', $orderEndpoint, $client->signKidPayload($orderEndpoint, $this->getResourceAccount(), null));
if (!isset($response['authorizations']) || !$response['authorizations']) {
throw new ChallengeNotSupportedException();
}
$authorizationsChallenges = [];
foreach ($response['authorizations'] as $authorizationEndpoint) {
$authorizationsResponse = $client->request('POST', $authorizationEndpoint, $client->signKidPayload($authorizationEndpoint, $this->getResourceAccount(), null));
$domain = (empty($authorizationsResponse['wildcard']) ? '' : '*.').$authorizationsResponse['identifier']['value'];
foreach ($authorizationsResponse['challenges'] as $challenge) {
$authorizationsChallenges[$domain][] = $this->createAuthorizationChallenge($authorizationsResponse['identifier']['value'], $challenge);
}
}
return new CertificateOrder($authorizationsChallenges, $orderEndpoint, $response['status']);
}
/**
* {@inheritdoc}
*/
public function finalizeOrder(CertificateOrder $order, CertificateRequest $csr, int $timeout = 180, bool $returnAlternateCertificateIfAvailable = false): CertificateResponse
{
$endTime = time() + $timeout;
$client = $this->getHttpClient();
$orderEndpoint = $order->getOrderEndpoint();
$response = $client->request('POST', $orderEndpoint, $client->signKidPayload($orderEndpoint, $this->getResourceAccount(), null));
if (\in_array($response['status'], ['pending', 'processing', 'ready'])) {
$humanText = ['-----BEGIN CERTIFICATE REQUEST-----', '-----END CERTIFICATE REQUEST-----'];
$csrContent = $this->csrSigner->signCertificateRequest($csr);
$csrContent = trim(str_replace($humanText, '', $csrContent));
$csrContent = trim($client->getBase64Encoder()->encode(base64_decode($csrContent)));
$response = $client->request('POST', $response['finalize'], $client->signKidPayload($response['finalize'], $this->getResourceAccount(), ['csr' => $csrContent]));
}
// Waiting loop
while (time() <= $endTime && (!isset($response['status']) || \in_array($response['status'], ['pending', 'processing', 'ready']))) {
sleep(1);
$response = $client->request('POST', $orderEndpoint, $client->signKidPayload($orderEndpoint, $this->getResourceAccount(), null));
}
if ('valid' !== $response['status']) {
throw new CertificateRequestFailedException('The order has not been validated');
}
$response = $client->rawRequest('POST', $response['certificate'], $client->signKidPayload($response['certificate'], $this->getResourceAccount(), null));
$responseHeaders = $response->getHeaders();
if ($returnAlternateCertificateIfAvailable && isset($responseHeaders['Link'][1])) {
$matches = [];
preg_match('/<(http.*)>;rel="alternate"/', $responseHeaders['Link'][1], $matches);
// If response headers include a valid alternate certificate link, return that certificate instead
if (isset($matches[1])) {
return $this->createCertificateResponse(
$csr,
$client->request('POST', $matches[1], $client->signKidPayload($matches[1], $this->getResourceAccount(), null), false)
);
}
}
return $this->createCertificateResponse($csr, Utils::copyToString($response->getBody()));
}
/**
* {@inheritdoc}
*/
public function requestAuthorization(string $domain): array
{
$order = $this->requestOrder([$domain]);
try {
return $order->getAuthorizationChallenges($domain);
} catch (AcmeCoreClientException $e) {
throw new ChallengeNotSupportedException();
}
}
/**
* {@inheritdoc}
*/
public function reloadAuthorization(AuthorizationChallenge $challenge): AuthorizationChallenge
{
$client = $this->getHttpClient();
$challengeUrl = $challenge->getUrl();
$response = (array) $client->request('POST', $challengeUrl, $client->signKidPayload($challengeUrl, $this->getResourceAccount(), null));
return $this->createAuthorizationChallenge($challenge->getDomain(), $response);
}
/**
* {@inheritdoc}
*/
public function challengeAuthorization(AuthorizationChallenge $challenge, int $timeout = 180): array
{
$endTime = time() + $timeout;
$client = $this->getHttpClient();
$challengeUrl = $challenge->getUrl();
$response = (array) $client->request('POST', $challengeUrl, $client->signKidPayload($challengeUrl, $this->getResourceAccount(), null));
if ('pending' === $response['status'] || 'processing' === $response['status']) {
$response = (array) $client->request('POST', $challengeUrl, $client->signKidPayload($challengeUrl, $this->getResourceAccount(), []));
}
// Waiting loop
while (time() <= $endTime && (!isset($response['status']) || 'pending' === $response['status'] || 'processing' === $response['status'])) {
sleep(1);
$response = (array) $client->request('POST', $challengeUrl, $client->signKidPayload($challengeUrl, $this->getResourceAccount(), null));
}
if (isset($response['status']) && ('pending' === $response['status'] || 'processing' === $response['status'])) {
throw new ChallengeTimedOutException($response);
}
if (!isset($response['status']) || 'valid' !== $response['status']) {
throw new ChallengeFailedException($response);
}
return $response;
}
/**
* {@inheritdoc}
*/
public function requestCertificate(string $domain, CertificateRequest $csr, int $timeout = 180, bool $returnAlternateCertificateIfAvailable = false): CertificateResponse
{
$order = $this->requestOrder(array_unique(array_merge([$domain], $csr->getDistinguishedName()->getSubjectAlternativeNames())));
return $this->finalizeOrder($order, $csr, $timeout, $returnAlternateCertificateIfAvailable);
}
/**
* {@inheritdoc}
*/
public function revokeCertificate(Certificate $certificate, RevocationReason $revocationReason = null)
{
if (!$endpoint = $this->getResourceUrl(ResourcesDirectory::REVOKE_CERT)) {
throw new CertificateRevocationException('This ACME server does not support certificate revocation.');
}
if (null === $revocationReason) {
$revocationReason = RevocationReason::createDefaultReason();
}
openssl_x509_export(openssl_x509_read($certificate->getPEM()), $formattedPem);
$formattedPem = str_ireplace('-----BEGIN CERTIFICATE-----', '', $formattedPem);
$formattedPem = str_ireplace('-----END CERTIFICATE-----', '', $formattedPem);
$client = $this->getHttpClient();
$formattedPem = $client->getBase64Encoder()->encode(base64_decode(trim($formattedPem)));
try {
$client->request(
'POST',
$endpoint,
$client->signKidPayload($endpoint, $this->getResourceAccount(), ['certificate' => $formattedPem, 'reason' => $revocationReason->getReasonType()]),
false
);
} catch (AcmeCoreServerException $e) {
throw new CertificateRevocationException($e->getMessage(), $e);
} catch (AcmeCoreClientException $e) {
throw new CertificateRevocationException($e->getMessage(), $e);
}
}
/**
* Find a resource URL from the Certificate Authority.
*/
public function getResourceUrl(string $resource): string
{
if (!$this->directory) {
$this->directory = new ResourcesDirectory(
$this->getHttpClient()->request('GET', $this->directoryUrl)
);
}
return $this->directory->getResourceUrl($resource);
}
/**
* Request a resource (URL is found using ACME server directory).
*
* @throws AcmeCoreServerException when the ACME server returns an error HTTP status code
* @throws AcmeCoreClientException when an error occured during response parsing
*
* @return array|string
*/
protected function requestResource(string $method, string $resource, array $payload, bool $returnJson = true)
{
$client = $this->getHttpClient();
$endpoint = $this->getResourceUrl($resource);
return $client->request(
$method,
$endpoint,
$client->signJwkPayload($endpoint, $payload),
$returnJson
);
}
private function createCertificateResponse(CertificateRequest $csr, string $certificate): CertificateResponse
{
$certificateHeader = '-----BEGIN CERTIFICATE-----';
$certificatesChain = null;
foreach (array_reverse(explode($certificateHeader, $certificate)) as $pem) {
if ('' !== \trim($pem)) {
$certificatesChain = new Certificate($certificateHeader.$pem, $certificatesChain);
}
}
return new CertificateResponse($csr, $certificatesChain);
}
private function getResourceAccount(): string
{
if (!$this->account) {
$payload = [
'onlyReturnExisting' => true,
];
$this->requestResource('POST', ResourcesDirectory::NEW_ACCOUNT, $payload);
$this->account = $this->getHttpClient()->getLastLocation();
}
return $this->account;
}
private function createAuthorizationChallenge($domain, array $response): AuthorizationChallenge
{
$base64encoder = $this->getHttpClient()->getBase64Encoder();
return new AuthorizationChallenge(
$domain,
$response['status'],
$response['type'],
$response['url'],
$response['token'],
$response['token'].'.'.$base64encoder->encode($this->getHttpClient()->getJWKThumbprint())
);
}
private function getHttpClient(): SecureHttpClient
{
if (!$this->initializedHttpClient) {
$this->initializedHttpClient = $this->uninitializedHttpClient;
$this->initializedHttpClient->setNonceEndpoint($this->getResourceUrl(ResourcesDirectory::NEW_NONCE));
}
return $this->initializedHttpClient;
}
}