-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathLescript.php
633 lines (499 loc) · 19.9 KB
/
Lescript.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
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
626
627
628
629
630
631
632
633
<?php
namespace Analogic\ACME;
use \RuntimeException;
use \Psr\Log\LoggerInterface;
class Lescript
{
public $ca = 'https://acme-v02.api.letsencrypt.org';
//public $ca = 'https://acme-staging-v02.api.letsencrypt.org'; // testing
public $countryCode = 'CZ';
public $state = "Czech Republic";
public $challenge = 'http-01'; // http-01 challange only
public $contact = array(); // optional
// public $contact = array("mailto:[email protected]", "tel:+12025551212")
public $clientUserAgent = "analogic-lescript/0.3.0";
protected $certificatesDir;
protected $webRootDir;
/** @var LoggerInterface */
protected $logger;
/** @var ClientInterface */
protected $client;
protected $accountKeyPath;
protected $accountId = '';
protected $urlNewAccount = '';
protected $urlNewNonce = '';
protected $urlNewOrder = '';
public function __construct($certificatesDir, $webRootDir, $logger = null, ClientInterface $client = null)
{
$this->certificatesDir = $certificatesDir;
$this->webRootDir = $webRootDir;
$this->logger = $logger;
$this->client = $client ? $client : new Client($this->ca, $this->clientUserAgent);
$this->accountKeyPath = $certificatesDir . '/_account/private.pem';
}
public function initAccount()
{
$this->initCommunication();
if (!is_file($this->accountKeyPath)) {
// generate and save new private key for account
// ---------------------------------------------
$this->log('Starting new account registration');
$this->generateKey(dirname($this->accountKeyPath));
$this->postNewReg();
$this->log('New account certificate registered');
} else {
$this->log('Account already registered. Continuing.');
$this->getAccountId();
}
if (empty($this->accountId)) {
throw new RuntimeException("We don't have account ID");
}
$this->log("Account: " . $this->accountId);
}
public function initCommunication()
{
$this->log('ACME Client: '.$this->clientUserAgent);
$this->log('Getting list of URLs for API');
$directory = $this->client->get('/directory');
if (!isset($directory['newNonce']) || !isset($directory['newAccount']) || !isset($directory['newOrder'])) {
throw new RuntimeException("Missing setup urls");
}
$this->urlNewNonce = $directory['newNonce'];
$this->urlNewAccount = $directory['newAccount'];
$this->urlNewOrder = $directory['newOrder'];
$this->log('Requesting new nonce for client communication');
$this->client->get($this->urlNewNonce);
}
public function signDomains(array $domains, $reuseCsr = false)
{
$this->log('Starting certificate generation process for domains');
$privateAccountKey = $this->readPrivateKey($this->accountKeyPath);
$accountKeyDetails = openssl_pkey_get_details($privateAccountKey);
// start domains authentication
// ----------------------------
$this->log("Requesting challenge for " . join(', ', $domains));
$response = $this->signedRequest(
$this->urlNewOrder,
array("identifiers" => array_map(
function ($domain) {
return array("type" => "dns", "value" => $domain);
},
$domains
))
);
$finalizeUrl = $response['finalize'];
foreach ($response['authorizations'] as $authz) {
// 1. getting authentication requirements
// --------------------------------------
$response = $this->signedRequest($authz, "");
$domain = $response['identifier']['value'];
if (empty($response['challenges'])) {
throw new RuntimeException("HTTP Challenge for $domain is not available. Whole response: " . json_encode($response));
}
$self = $this;
$challenge = array_reduce($response['challenges'], function ($v, $w) use (&$self) {
return $v ? $v : ($w['type'] == $self->challenge ? $w : false);
});
if (!$challenge) throw new RuntimeException("HTTP Challenge for $domain is not available. Whole response: " . json_encode($response));
$this->log("Got challenge token for $domain");
// 2. saving authentication token for web verification
// ---------------------------------------------------
$directory = $this->webRootDir . '/.well-known/acme-challenge';
$tokenPath = $directory . '/' . $challenge['token'];
if (!file_exists($directory) && !@mkdir($directory, 0755, true)) {
throw new RuntimeException("Couldn't create directory to expose challenge: ${tokenPath}");
}
$header = array(
// need to be in precise order!
"e" => Base64UrlSafeEncoder::encode($accountKeyDetails["rsa"]["e"]),
"kty" => "RSA",
"n" => Base64UrlSafeEncoder::encode($accountKeyDetails["rsa"]["n"])
);
$payload = $challenge['token'] . '.' . Base64UrlSafeEncoder::encode(hash('sha256', json_encode($header), true));
file_put_contents($tokenPath, $payload);
chmod($tokenPath, 0644);
// 3. verification process itself
// -------------------------------
$uri = "http://${domain}/.well-known/acme-challenge/${challenge['token']}";
$this->log("Token for $domain saved at $tokenPath and should be available at $uri");
$this->log("Sending request to challenge");
// send request to challenge
$maxAllowedLoops = 6;
$loopCount = 1;
$result = null;
while ($loopCount < $maxAllowedLoops) {
$result = $this->signedRequest(
$challenge['url'],
array("keyAuthorization" => $payload)
);
if (empty($result['status']) || $result['status'] == "invalid") {
throw new RuntimeException("Verification ended with error: " . json_encode($result));
}
if ($result['status'] != "pending") {
break;
}
$sleepTime = $loopCount * $loopCount; // 1 4 9 16 25 36
$loopCount++;
$this->log("Verification pending, sleeping " . $sleepTime . "s");
sleep($sleepTime);
}
if ($result['status'] === "pending") {
throw new RuntimeException("Verification timed out");
}
$this->log("Verification ended with status: ${result['status']}");
@unlink($tokenPath);
}
// requesting certificate
// ----------------------
$domainPath = $this->getDomainPath(reset($domains));
// generate private key for domain if not exist
if (!is_dir($domainPath) || !is_file($domainPath . '/private.pem')) {
$this->generateKey($domainPath);
}
// load domain key
$privateDomainKey = $this->readPrivateKey($domainPath . '/private.pem');
$this->client->getLastLinks();
$csr = $reuseCsr && is_file($domainPath . "/last.csr") ?
$this->getCsrContent($domainPath . "/last.csr") :
$this->generateCSR($privateDomainKey, $domains);
$finalizeResponse = $this->signedRequest($finalizeUrl, array('csr' => $csr));
if ($this->client->getLastCode() > 299 || $this->client->getLastCode() < 200) {
throw new RuntimeException("Invalid response code: " . $this->client->getLastCode() . ", " . json_encode($finalizeResponse));
}
$maxAllowedLoops = 6;
$loopCount = 1;
while ($loopCount < $maxAllowedLoops) {
$this->log("Firing Order Status Request Nr. " . $loopCount . " to: " . $this->client->getLastLocation());
$OrderStatusResponse = $this->signedRequest($this->client->getLastLocation(), "");
if (($this->client->getLastCode() > 299 || $this->client->getLastCode() < 200)) {
throw new RuntimeException("Invalid response code: " . $this->client->getLastCode() . ", " . json_encode($OrderStatusResponse));
}
if (($OrderStatusResponse['status'] == "valid" && !empty($OrderStatusResponse['certificate']))) {
$this->log("Order Status: " . $OrderStatusResponse['status']);
$location = $OrderStatusResponse['certificate'];
break;
}
$sleepTime = $loopCount * $loopCount; // 1 4 9 16 25 36
$loopCount++;
$this->log("Order Status not 'valid' yet but '" . $OrderStatusResponse['status'] . "', sleeping " . $sleepTime . "s");
sleep($sleepTime);
}
if (empty($location)) {
throw new RuntimeException("Certificate generation processing timed out (Status not 'valid')");
}
// waiting loop
$certificates = array();
while (1) {
$this->client->getLastLinks();
$result = $this->signedRequest($location, "");
if ($this->client->getLastCode() == 202) {
$this->log("Certificate generation pending, sleeping 1s");
sleep(1);
} else if ($this->client->getLastCode() == 200) {
$this->log("Got certificate! YAY!");
$serverCert = $this->parseFirstPemFromBody($result);
$certificates[] = $serverCert;
$certificates[] = substr($result, strlen($serverCert)); // rest of ca certs
break;
} else {
throw new RuntimeException("Can't get certificate: HTTP code " . $this->client->getLastCode());
}
}
if (empty($certificates)) throw new RuntimeException('No certificates generated');
$this->log("Saving fullchain.pem");
file_put_contents($domainPath . '/fullchain.pem', implode("\n", $certificates));
$this->log("Saving cert.pem");
file_put_contents($domainPath . '/cert.pem', array_shift($certificates));
$this->log("Saving chain.pem");
file_put_contents($domainPath . "/chain.pem", implode("\n", $certificates));
$this->log("Done !!§§!");
}
protected function readPrivateKey($path)
{
if (($key = openssl_pkey_get_private('file://' . $path)) === FALSE) {
throw new RuntimeException(openssl_error_string());
}
return $key;
}
protected function parseFirstPemFromBody($body)
{
preg_match('~(-----BEGIN.*?END CERTIFICATE-----)~s', $body, $matches);
return $matches[1];
}
protected function getDomainPath($domain)
{
return $this->certificatesDir . '/' . $domain . '/';
}
protected function getAccountId()
{
return $this->postNewReg();
}
protected function postNewReg()
{
$data = array(
'termsOfServiceAgreed' => true
);
$this->log('Sending registration to letsencrypt server');
if ($this->contact) {
$data['contact'] = $this->contact;
}
$response = $this->signedRequest(
$this->urlNewAccount,
$data
);
$lastLocation = $this->client->getLastLocation();
if (!empty($lastLocation)) {
$this->accountId = $lastLocation;
}
return $response;
}
protected function generateCSR($privateKey, array $domains)
{
$domain = reset($domains);
$san = implode(",", array_map(function ($dns) {
return "DNS:" . $dns;
}, $domains));
$tmpConf = tmpfile();
$tmpConfMeta = stream_get_meta_data($tmpConf);
$tmpConfPath = $tmpConfMeta["uri"];
// workaround to get SAN working
fwrite($tmpConf,
'HOME = .
RANDFILE = $ENV::HOME/.rnd
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
[ v3_req ]
basicConstraints = CA:FALSE
subjectAltName = ' . $san . '
keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
$csr = openssl_csr_new(
array(
"CN" => $domain,
"ST" => $this->state,
"C" => $this->countryCode,
"O" => "Unknown",
),
$privateKey,
array(
"config" => $tmpConfPath,
"digest_alg" => "sha256"
)
);
if (!$csr) throw new RuntimeException("CSR couldn't be generated! " . openssl_error_string());
openssl_csr_export($csr, $csr);
fclose($tmpConf);
$csrPath = $this->getDomainPath($domain) . "/last.csr";
file_put_contents($csrPath, $csr);
return $this->getCsrContent($csrPath);
}
protected function getCsrContent($csrPath)
{
$csr = file_get_contents($csrPath);
preg_match('~REQUEST-----(.*)-----END~s', $csr, $matches);
return trim(Base64UrlSafeEncoder::encode(base64_decode($matches[1])));
}
protected function generateKey($outputDirectory)
{
$res = openssl_pkey_new(array(
"private_key_type" => OPENSSL_KEYTYPE_RSA,
"private_key_bits" => 4096,
));
if (!openssl_pkey_export($res, $privateKey)) {
throw new RuntimeException("Key export failed!");
}
$details = openssl_pkey_get_details($res);
if (!is_dir($outputDirectory)) @mkdir($outputDirectory, 0700, true);
if (!is_dir($outputDirectory)) throw new RuntimeException("Cant't create directory $outputDirectory");
file_put_contents($outputDirectory . '/private.pem', $privateKey);
file_put_contents($outputDirectory . '/public.pem', $details['key']);
}
protected function signedRequest($uri, $payload, $nonce = null)
{
$privateKey = $this->readPrivateKey($this->accountKeyPath);
$details = openssl_pkey_get_details($privateKey);
$protected = array(
"alg" => "RS256",
"nonce" => $nonce ? $nonce : $this->client->getLastNonce(),
"url" => $uri
);
if ($this->accountId) {
$protected["kid"] = $this->accountId;
} else {
$protected["jwk"] = array(
"kty" => "RSA",
"n" => Base64UrlSafeEncoder::encode($details["rsa"]["n"]),
"e" => Base64UrlSafeEncoder::encode($details["rsa"]["e"]),
);
}
$payload64 = Base64UrlSafeEncoder::encode(empty($payload) ? "" : str_replace('\\/', '/', json_encode($payload)));
$protected64 = Base64UrlSafeEncoder::encode(json_encode($protected));
openssl_sign($protected64 . '.' . $payload64, $signed, $privateKey, "SHA256");
$signed64 = Base64UrlSafeEncoder::encode($signed);
$data = array(
'protected' => $protected64,
'payload' => $payload64,
'signature' => $signed64
);
$this->log("Sending signed request to $uri");
return $this->client->post($uri, json_encode($data));
}
protected function log($message)
{
if ($this->logger) {
$this->logger->info($message);
} else {
echo $message . "\n";
}
}
}
interface ClientInterface
{
/**
* Constructor
*
* @param string $base the ACME API base all relative requests are sent to
* @param string $userAgent ACME Client User-Agent
*/
public function __construct($base, $userAgent);
/**
* Send a POST request
*
* @param string $url URL to post to
* @param array $data fields to sent via post
* @return array|string the parsed JSON response, raw response on error
*/
public function post($url, $data);
/**
* @param string $url URL to request via get
* @return array|string the parsed JSON response, raw response on error
*/
public function get($url);
/**
* Returns the Replay-Nonce header of the last request
*
* if no request has been made, yet. A GET on $base/directory is done and the
* resulting nonce returned
*
* @return mixed
*/
public function getLastNonce();
/**
* Return the Location header of the last request
*
* returns null if last request had no location header
*
* @return string|null
*/
public function getLastLocation();
/**
* Return the HTTP status code of the last request
*
* @return int
*/
public function getLastCode();
/**
* Get all Link headers of the last request
*
* @return string[]
*/
public function getLastLinks();
}
class Client implements ClientInterface
{
protected $lastCode;
protected $lastHeader;
protected $base;
protected $userAgent;
public function __construct($base, $userAgent)
{
$this->base = $base;
$this->userAgent = $userAgent;
}
protected function curl($method, $url, $data = null)
{
$headers = array('Accept: application/json', 'Content-Type: application/jose+json');
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, preg_match('~^http~', $url) ? $url : $this->base . $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HEADER, true);
curl_setopt($handle, CURLOPT_USERAGENT, $this->userAgent);
// DO NOT DO THAT!
// curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
switch ($method) {
case 'GET':
break;
case 'POST':
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
}
$response = curl_exec($handle);
if (curl_errno($handle)) {
throw new RuntimeException('Curl: ' . curl_error($handle));
}
$header_size = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$this->lastHeader = $header;
$this->lastCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($this->lastCode >= 400 && $this->lastCode < 600) {
throw new RuntimeException($this->lastCode . "\n" . $body);
}
$data = json_decode($body, true);
return $data === null ? $body : $data;
}
public function post($url, $data)
{
return $this->curl('POST', $url, $data);
}
public function get($url)
{
return $this->curl('GET', $url);
}
public function getLastNonce()
{
if (preg_match('~Replay-Nonce: (.+)~i', $this->lastHeader, $matches)) {
return trim($matches[1]);
}
throw new RuntimeException("We don't have nonce");
}
public function getLastLocation()
{
if (preg_match('~Location: (.+)~i', $this->lastHeader, $matches)) {
return trim($matches[1]);
}
return null;
}
public function getLastCode()
{
return $this->lastCode;
}
public function getLastLinks()
{
preg_match_all('~Link: <(.+)>;rel="up"~', $this->lastHeader, $matches);
return $matches[1];
}
}
class Base64UrlSafeEncoder
{
public static function encode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
public static function decode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
}