forked from analogic/lescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lescript.php
485 lines (373 loc) · 15 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
<?php
namespace Analogic\ACME;
class Lescript
{
public $ca = 'https://acme-v01.api.letsencrypt.org';
// public $ca = 'https://acme-staging.api.letsencrypt.org'; // testing
public $license = 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf';
public $countryCode = 'CZ';
public $state = "Czech Republic";
private $certificatesDir;
private $webRootDir;
/** @var \Psr\Log\LoggerInterface */
private $logger;
private $client;
private $accountKeyPath;
public function __construct($certificatesDir, $webRootDir, $logger = null)
{
$this->certificatesDir = $certificatesDir;
$this->webRootDir = $webRootDir;
$this->logger = $logger;
$this->client = new Client($this->ca);
$this->accountKeyPath = $certificatesDir . '/_account/private.pem';
}
public function initAccount()
{
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.');
}
}
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
// ----------------------------
foreach ($domains as $domain) {
// 1. getting available authentication options
// -------------------------------------------
$this->log("Requesting challenge for $domain");
$response = $this->signedRequest(
"/acme/new-authz",
array("resource" => "new-authz", "identifier" => array("type" => "dns", "value" => $domain))
);
// choose http-01 challange only
$challenge = array_reduce($response['challenges'], function ($v, $w) {
return $v ? $v : ($w['type'] == 'http-01' ? $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");
$location = $this->client->getLastLocation();
// 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");
// simple self check
if ($payload !== trim(@file_get_contents($uri))) {
throw new \RuntimeException("Please check $uri - token not available");
}
$this->log("Sending request to challenge");
// send request to challenge
$result = $this->signedRequest(
$challenge['uri'],
array(
"resource" => "challenge",
"type" => "http-01",
"keyAuthorization" => $payload,
"token" => $challenge['token']
)
);
// waiting loop
do {
if (empty($result['status']) || $result['status'] == "invalid") {
throw new \RuntimeException("Verification ended with error: " . json_encode($result));
}
$ended = !($result['status'] === "pending");
if (!$ended) {
$this->log("Verification pending, sleeping 1s");
sleep(1);
}
$result = $this->client->get($location);
} while (!$ended);
$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);
// request certificates creation
$result = $this->signedRequest(
"/acme/new-cert",
array('resource' => 'new-cert', 'csr' => $csr)
);
if ($this->client->getLastCode() !== 201) {
throw new \RuntimeException("Invalid response code: " . $this->client->getLastCode() . ", " . json_encode($result));
}
$location = $this->client->getLastLocation();
// waiting loop
$certificates = array();
while (1) {
$this->client->getLastLinks();
$result = $this->client->get($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!");
$certificates[] = $this->parsePemFromBody($result);
foreach ($this->client->getLastLinks() as $link) {
$this->log("Requesting chained cert at $link");
$result = $this->client->get($link);
$certificates[] = $this->parsePemFromBody($result);
}
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 !!§§!");
}
private function readPrivateKey($path)
{
if (($key = openssl_pkey_get_private('file://' . $path)) === FALSE) {
throw new \RuntimeException(openssl_error_string());
}
return $key;
}
private function parsePemFromBody($body)
{
$pem = chunk_split(base64_encode($body), 64, "\n");
return "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
}
private function getDomainPath($domain)
{
return $this->certificatesDir . '/' . $domain . '/';
}
private function postNewReg()
{
$this->log('Sending registration to letsencrypt server');
return $this->signedRequest(
'/acme/new-reg',
array('resource' => 'new-reg', 'agreement' => $this->license)
);
}
private 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);
}
private function getCsrContent($csrPath) {
$csr = file_get_contents($csrPath);
preg_match('~REQUEST-----(.*)-----END~s', $csr, $matches);
return trim(Base64UrlSafeEncoder::encode(base64_decode($matches[1])));
}
private 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']);
}
private function signedRequest($uri, array $payload)
{
$privateKey = $this->readPrivateKey($this->accountKeyPath);
$details = openssl_pkey_get_details($privateKey);
$header = array(
"alg" => "RS256",
"jwk" => array(
"kty" => "RSA",
"n" => Base64UrlSafeEncoder::encode($details["rsa"]["n"]),
"e" => Base64UrlSafeEncoder::encode($details["rsa"]["e"]),
)
);
$protected = $header;
$protected["nonce"] = $this->client->getLastNonce();
$payload64 = Base64UrlSafeEncoder::encode(str_replace('\\/', '/', json_encode($payload)));
$protected64 = Base64UrlSafeEncoder::encode(json_encode($protected));
openssl_sign($protected64.'.'.$payload64, $signed, $privateKey, "SHA256");
$signed64 = Base64UrlSafeEncoder::encode($signed);
$data = array(
'header' => $header,
'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";
}
}
}
class Client
{
private $lastCode;
private $lastHeader;
private $base;
public function __construct($base)
{
$this->base = $base;
}
private function curl($method, $url, $data = null)
{
$headers = array('Accept: application/json', 'Content-Type: application/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);
// 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);
$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]);
}
$this->curl('GET', '/directory');
return $this->getLastNonce();
}
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, '-_', '+/'));
}
}