-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathLE.pm
More file actions
2224 lines (1774 loc) · 80 KB
/
LE.pm
File metadata and controls
2224 lines (1774 loc) · 80 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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Crypt::LE;
use 5.006;
use strict;
use warnings;
our $VERSION = '0.40';
=head1 NAME
Crypt::LE - Let's Encrypt (and other ACME-based) API interfacing module and client.
=head1 VERSION
Version 0.40
=head1 SYNOPSIS
use Crypt::LE;
my $le = Crypt::LE->new();
$le->load_account_key('account.pem');
$le->load_csr('domain.csr');
$le->register();
$le->accept_tos();
$le->request_challenge();
$le->accept_challenge(\&process_challenge);
$le->verify_challenge();
$le->request_certificate();
my $cert = $le->certificate();
...
sub process_challenge {
my $challenge = shift;
print "Challenge for $challenge->{domain} requires:\n";
print "A file '/.well-known/acme-challenge/$challenge->{token}' with the text: $challenge->{token}.$challenge->{fingerprint}\n";
print "When done, press <Enter>";
<STDIN>;
return 1;
};
=head1 DESCRIPTION
Crypt::LE provides the functionality necessary to use Let's Encrypt API and generate free SSL certificates for your domains. It can also
be used to generate RSA keys and Certificate Signing Requests or to revoke previously issued certificates. Crypt::LE is shipped with a
self-sufficient client for obtaining SSL certificates - le.pl.
B<Provided client supports 'http' and 'dns' domain verification out of the box.>
Crypt::LE can be easily extended with custom plugins to handle Let's Encrypt challenges. See L<Crypt::LE::Challenge::Simple> module
for an example of a challenge-handling plugin.
Basic usage:
B<le.pl --key account.key --csr domain.csr --csr-key domain.key --crt domain.crt --domains "www.domain.ext,domain.ext" --generate-missing>
That will generate an account key and a CSR (plus key) if they are missing. If any of those files exist, they will just be loaded, so it is safe to re-run
the client. Run le.pl without any parameters or with C<--help> to see more details and usage examples.
In addition to challenge-handling plugins, the client also supports completion-handling plugins, such as L<Crypt::LE::Complete::Simple>. You can easily
handle challenges and trigger specific actions when your certificate gets issued by using those modules as templates, without modifying the client code.
You can also pass custom parameters to your modules from le.pl command line:
B<le.pl ... --handle-with Crypt::LE::Challenge::Simple --handle-params '{"key1": 1, "key2": "one"}'>
B<le.pl ... --complete-with Crypt::LE::Complete::Simple --complete-params '{"key1": 1, "key2": "one"}'>
The parameters don't have to be put directly in the command line, you could also give a name of a file containing valid JSON to read them from.
B<le.pl ... --complete-params complete.json>
Crypt::LE::Challenge:: and Crypt::LE::Complete:: namespaces are suggested for new plugins.
=head1 EXPORT
Crypt::LE does not export anything by default, but allows you to import the following constants:
=over
=item *
OK
=item *
READ_ERROR
=item *
LOAD_ERROR
=item *
INVALID_DATA
=item *
DATA_MISMATCH
=item *
UNSUPPORTED
=item *
ALREADY_DONE
=item *
BAD_REQUEST
=item *
AUTH_ERROR
=item *
ERROR
=back
To import all of those, use C<':errors'> tag:
use Crypt::LE ':errors';
...
$le->load_account_key('account.pem') == OK or die "Could not load the account key: " . $le->error_details;
If you don't want to use error codes while checking whether the last called method has failed or not, you can use the
rule of thumb that on success it will return zero. You can also call error() or error_details() methods, which
will be set with some values on error.
=cut
use Crypt::OpenSSL::RSA;
use JSON::MaybeXS;
use HTTP::Tiny;
use IO::File;
use Digest::SHA qw<sha256 hmac_sha256>;
use MIME::Base64 qw<encode_base64url decode_base64url decode_base64 encode_base64>;
use Net::SSLeay qw<XN_FLAG_RFC2253 ASN1_STRFLGS_ESC_MSB MBSTRING_UTF8>;
use Scalar::Util 'blessed';
use Encode 'encode_utf8';
use Storable 'dclone';
use Convert::ASN1;
use Module::Load;
use Time::Piece;
use Time::Seconds;
use Data::Dumper;
use base 'Exporter';
Net::SSLeay::randomize();
Net::SSLeay::load_error_strings();
Net::SSLeay::ERR_load_crypto_strings();
Net::SSLeay::OpenSSL_add_ssl_algorithms();
Net::SSLeay::OpenSSL_add_all_digests();
our $keysize = 4096;
our $keycurve = 'prime256v1';
our $headers = { 'Content-type' => 'application/jose+json' };
our $default_ca = 'letsencrypt.org';
our $cas = {
'letsencrypt.org' => {
'live' => 'https://acme-v02.api.letsencrypt.org/directory',
'stage' => 'https://acme-staging-v02.api.letsencrypt.org/directory',
},
'buypass.com' => {
'live' => 'https://api.buypass.com/acme/directory',
'stage' => 'https://api.test4.buypass.no/acme/directory',
},
'ssl.com' => {
'live' => 'https://acme.ssl.com/sslcom-dv-rsa',
},
'zerossl.com' => {
'live' => 'https://acme.zerossl.com/v2/DV90/directory',
},
'google.com' => {
'live' => 'https://dv.acme-v02.api.pki.goog/directory',
'stage' => 'https://dv.acme-v02.test-api.pki.goog/directory',
},
'sectigo.com' => {
'live' => 'https://acme.sectigo.com/v2/DV',
},
};
use constant {
OK => 0,
READ_ERROR => 1,
LOAD_ERROR => 2,
INVALID_DATA => 3,
DATA_MISMATCH => 4,
UNSUPPORTED => 5,
ERROR => 500,
SUCCESS => 200,
CREATED => 201,
ACCEPTED => 202,
BAD_REQUEST => 400,
AUTH_ERROR => 403,
ALREADY_DONE => 409,
KEY_RSA => 0,
KEY_ECC => 1,
PEER_CRT => 4,
CRT_DEPTH => 5,
SAN => '2.5.29.17',
};
our @EXPORT_OK = (qw<OK READ_ERROR LOAD_ERROR INVALID_DATA DATA_MISMATCH UNSUPPORTED ERROR BAD_REQUEST AUTH_ERROR ALREADY_DONE KEY_RSA KEY_ECC>);
our %EXPORT_TAGS = ( 'errors' => [ @EXPORT_OK[0..9] ], 'keys' => [ @EXPORT_OK[10..11] ] );
my $pkcs12_available = 0;
my $j = JSON->new->canonical()->allow_nonref();
my $url_safe = qr/^[-_A-Za-z0-9]+$/; # RFC 4648 section 5.
my $flag_rfc22536_utf8 = (XN_FLAG_RFC2253) & (~ ASN1_STRFLGS_ESC_MSB);
if ($^O eq 'MSWin32') {
eval { autoload 'Crypt::OpenSSL::PKCS12'; };
$pkcs12_available = 1 unless $@;
}
# https://github.com/letsencrypt/boulder/blob/master/core/good_key.go
my @primes = map { Crypt::OpenSSL::Bignum->new_from_decimal($_) } (
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283,
293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359,
367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431,
433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,
499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571,
577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709,
719, 727, 733, 739, 743, 751
);
my $asn = Convert::ASN1->new();
$asn->prepare(q<
Extensions ::= SEQUENCE OF Extension
Extension ::= SEQUENCE {
extnID OBJECT IDENTIFIER,
critical BOOLEAN OPTIONAL,
extnValue OCTET STRING
}
SubjectAltName ::= GeneralNames
GeneralNames ::= SEQUENCE OF GeneralName
GeneralName ::= CHOICE {
otherName [0] ANY,
rfc822Name [1] IA5String,
dNSName [2] IA5String,
x400Address [3] ANY,
directoryName [4] ANY,
ediPartyName [5] ANY,
uniformResourceIdentifier [6] IA5String,
iPAddress [7] OCTET STRING,
registeredID [8] OBJECT IDENTIFIER
}
>);
my $compat = {
newAccount => 'new-reg',
newOrder => 'new-cert',
revokeCert => 'revoke-cert',
};
# Subset of https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1 as supported by Boulder.
my $revocation_reasons = {
unspecified => 0,
keycompromise => 1,
affiliationchanged => 3,
superseded => 4,
cessationofoperation => 5,
};
=head1 METHODS (API Setup)
The following methods are provided for the API setup. Please note that account key setup by default requests the resource directory from Let's Encrypt servers.
This can be changed by resetting the 'autodir' parameter of the constructor.
=head2 new()
Create a new instance of the class. Initialize the object with passed parameters. Normally you don't need to use any, but the following are supported:
=over 12
=item C<ua>
User-agent name to use while sending requests to Let's Encrypt servers. By default set to module name and version.
=item C<server>
Server URL to connect to. Only needed if the default live or staging server URLs have changed and this module has not yet been updated with the new
information or if you are using a custom server supporting ACME protocol. Note: the value is supposed to point to the root of the API (for example:
https://some.server/acme/) rather than the directory handler. This parameter might be deprecated in the future in favour of the 'dir' one below.
=item C<live>
Set to true to connect to a live Let's Encrypt server. By default it is not set, so staging server is used, where you can test the whole process of getting
SSL certificates.
=item C<debug>
Activates printing debug messages to the standard output when set. If set to 1, only standard messages are printed. If set to any greater value, then structures and
server responses are printed as well.
=item C<dir>
Full URL of a 'directory' handler on the server (the actual name of the handler can be different in certain configurations, where multiple handlers
are mapped). Only needed if you are using a custom server supporting ACME protocol. This parameter replaces the 'server' one.
=item C<ca>
The name of CA (Certificate Authority) to use. If the name is found in the list of supported ones, the URLs to use will be automatically set.
Please note that this parameter will be ignored if the 'directory' or 'server' are explicitly set.
=item C<autodir>
Enables automatic retrieval of the resource directory (required for normal API processing) from the servers. Enabled by default.
=item C<delay>
Specifies the time in seconds to wait before the challenge verification results are checked again. By default set to 2 seconds.
Non-integer values are supported (so for example you can set it to 1.5 if you like). Please note that the server-specified delay overrides this value,
but it can be adjusted by using max_server_delay (see below).
=item C<max_server_delay>
Overrides server-specified delay in seconds to wait before the challenge verification results are checked again.
=item C<version>
Enforces the API version to be used. If the response is not found to be compatible, an error will be returned. If not set, system will try to make an educated guess.
=item C<try>
Specifies the amount of retries to attempt while in 'pending' state and waiting for verification results response. By default set to 300, which combined
with the delay of 2 seconds gives you 10 minutes of waiting.
=item C<logger>
Logger instance to use for debug messages. If not given, the messages will be printed to STDOUT.
=back
Returns: L<Crypt::LE> object.
=cut
sub new {
my $class = shift;
my %params = @_;
my $self = {
ua => '',
server => '',
ca => '',
dir => '',
live => 0,
debug => 0,
autodir => 1,
delay => 0,
max_server_delay => 0,
version => 0,
try => 300,
};
foreach my $key (keys %{$self}) {
$self->{$key} = $params{$key} if (exists $params{$key} and !ref $params{$key});
}
# Some defaults.
$self->{delay} ||= 2;
# Init UA
$self->{ua} = HTTP::Tiny->new( agent => $self->{ua} || __PACKAGE__ . " v$VERSION", verify_SSL => 1 );
# Init server
my $opts;
if ($self->{server}) {
# Custom server - drop the protocol if given (defaults to https later). If that leaves nothing, the check below
# will set the servers to LE standard ones.
$self->{server}=~s~^\w+://~~;
} elsif ($self->{dir}) {
$self->{dir} = "https://$self->{dir}" unless $self->{dir}=~m~^https?://~i;
} elsif ($self->{ca}) {
$opts = $cas->{lc($self->{ca})} || $cas->{$default_ca};
} else {
$opts = $cas->{$default_ca};
}
if ($opts) {
# Only check for live option if the 'stage' is supported by CA. Otherwise use live URL.
if ($opts->{'stage'}) {
$self->{dir} = $self->{live} ? $opts->{live} : $opts->{stage};
} else {
$self->{dir} = $opts->{live};
}
}
# Init logger
$self->{logger} = $params{logger} if ($params{logger} and blessed $params{logger});
bless $self, $class;
}
#====================================================================================================
# API Setup functions
#====================================================================================================
=head2 load_account_key($filename|$scalar_ref)
Loads the private account key from the file or scalar in PEM or DER formats.
Returns: OK | READ_ERROR | LOAD_ERROR | INVALID_DATA.
=cut
sub load_account_key {
my ($self, $file) = @_;
$self->_reset_key;
my $key = $self->_file($file);
return $self->_status(READ_ERROR, "Key reading error.") unless $key;
eval {
$key = Crypt::OpenSSL::RSA->new_private_key($self->_convert($key, 'RSA PRIVATE KEY'));
};
return $self->_status(LOAD_ERROR, "Key loading error.") if $@;
return $self->_set_key($key, "Account key loaded.");
}
=head2 generate_account_key()
Generates a new private account key of the $keysize bits (4096 by default). The key is additionally validated for not being divisible by small primes.
Returns: OK | INVALID_DATA.
=cut
sub generate_account_key {
my $self = shift;
my ($pk, $err, $code) = _key();
return $self->_status(INVALID_DATA, $err||"Could not generate account key") unless $pk;
my $key = Crypt::OpenSSL::RSA->new_private_key(Net::SSLeay::PEM_get_string_PrivateKey($pk));
_free(k => $pk);
return $self->_set_key($key, "Account key generated.");
}
=head2 account_key()
Returns: A previously loaded or generated private key in PEM format or undef.
=cut
sub account_key {
return shift->{pem};
}
=head2 load_csr($filename|$scalar_ref [, $domains])
Loads Certificate Signing Requests from the file or scalar. Domains list can be omitted or it can be given as a string of comma-separated names or as an array reference.
If omitted, then names will be loaded from the CSR. If it is given, then the list of names will be verified against those found on CSR.
Returns: OK | READ_ERROR | LOAD_ERROR | INVALID_DATA | DATA_MISMATCH.
=cut
sub load_csr {
my $self = shift;
my ($file, $domains) = @_;
$self->_reset_csr;
my $csr = $self->_file($file);
return $self->_status(READ_ERROR, "CSR reading error.") unless $csr;
my $bio = Net::SSLeay::BIO_new(Net::SSLeay::BIO_s_mem());
return $self->_status(LOAD_ERROR, "Could not allocate memory for the CSR") unless $bio;
my ($in, $cn, $san, $i);
unless (Net::SSLeay::BIO_write($bio, $csr) and $in = Net::SSLeay::PEM_read_bio_X509_REQ($bio)) {
_free(b => $bio);
return $self->_status(LOAD_ERROR, "Could not load the CSR");
}
$cn = Net::SSLeay::X509_REQ_get_subject_name($in);
if ($cn) {
$cn = Net::SSLeay::X509_NAME_print_ex($cn, $flag_rfc22536_utf8, 1);
$cn = lc($1) if ($cn and $cn=~/^.*?\bCN=([^\s,]+).*$/);
}
my @list = @{$self->_get_list($domains)};
$i = Net::SSLeay::X509_REQ_get_attr_by_NID($in, &Net::SSLeay::NID_ext_req, -1);
if ($i > -1) {
my $o = Net::SSLeay::P_X509_REQ_get_attr($in, $i);
if ($o) {
my $exts = $asn->find("Extensions");
my $dec = $exts->decode(Net::SSLeay::P_ASN1_STRING_get($o));
if ($dec) {
foreach my $ext (@{$dec}) {
if ($ext->{extnID} and $ext->{extnID} eq SAN) {
$exts = $asn->find("SubjectAltName");
$san = $exts->decode($ext->{extnValue});
last;
}
}
}
}
}
my @loaded_domains = ();
my %seen = ();
my $san_broken;
if ($cn) {
push @loaded_domains, $cn;
$seen{$cn} = 1;
}
if ($san) {
foreach my $ext (@{$san}) {
if ($ext->{dNSName}) {
$cn = lc($ext->{dNSName});
push @loaded_domains, $cn unless $seen{$cn}++;
} else {
$san_broken++;
}
}
}
_free(b => $bio);
if ($san_broken) {
return $self->_status(INVALID_DATA, "CSR contains $san_broken non-DNS record(s) in SAN");
}
unless (@loaded_domains) {
return $self->_status(INVALID_DATA, "No domains found on CSR.");
} else {
if (my $odd = $self->_verify_list(\@loaded_domains)) {
return $self->_status(INVALID_DATA, "Unsupported domain names on CSR: " . join(", ", @{$odd}));
}
$self->_debug("Loaded domain names from CSR: " . join(', ', @loaded_domains));
}
if (@list) {
return $self->_status(DATA_MISMATCH, "The list of provided domains does not match the one on the CSR.") unless (join(',', sort @loaded_domains) eq join(',', sort @list));
@loaded_domains = @list; # Use the command line domain order if those were listed along with CSR.
}
$self->_set_csr($csr, undef, \@loaded_domains);
return $self->_status(OK, "CSR loaded.");
}
=head2 generate_csr($domains, [$key_type], [$key_attr])
Generates a new Certificate Signing Request. Optionally accepts key type and key attribute parameters, where key type should
be either KEY_RSA or KEY_ECC (if supported on your system) and key attribute is either the key size (for RSA) or the curve (for ECC).
By default an RSA key of 4096 bits will be used.
Domains list is mandatory and can be given as a string of comma-separated names or as an array reference.
Returns: OK | ERROR | UNSUPPORTED | INVALID_DATA.
=cut
sub generate_csr {
my $self = shift;
my ($domains, $key_type, $key_attr) = @_;
$self->_reset_csr;
my @list = @{$self->_get_list($domains)};
return $self->_status(INVALID_DATA, "No domains provided.") unless @list;
if (my $odd = $self->_verify_list(\@list)) {
return $self->_status(INVALID_DATA, "Unsupported domain names provided: " . join(", ", @{$odd}));
}
my ($key, $err, $code) = _key($self->csr_key(), $key_type, $key_attr);
return $self->_status($code||ERROR, $err||"Key problem while creating CSR") unless $key;
my ($csr, $csr_key) = _csr($key, \@list, { O => '-', L => '-', ST => '-', C => 'GB' });
return $self->_status(ERROR, "Unexpected CSR error.") unless $csr;
$self->_set_csr($csr, $csr_key, \@list);
return $self->_status(OK, "CSR generated.");
}
=head2 csr()
Returns: A previously loaded or generated CSR in PEM format or undef.
=cut
sub csr {
return shift->{csr};
}
=head2 load_csr_key($filename|$scalar_ref)
Loads the CSR key from the file or scalar (to be used for generating a new CSR).
Returns: OK | READ_ERROR.
=cut
sub load_csr_key {
my $self = shift;
my $file = shift;
undef $self->{csr_key};
my $key = $self->_file($file);
return $self->_status(READ_ERROR, "CSR key reading error.") unless $key;
$self->{csr_key} = $key;
return $self->_status(OK, "CSR key loaded");
}
=head2 csr_key()
Returns: A CSR key (either loaded or generated with CSR) or undef.
=cut
sub csr_key {
return shift->{csr_key};
}
=head2 set_account_email([$email])
Sets (or resets if no parameter is given) an email address that will be used for registration requests.
Returns: OK | INVALID_DATA.
=cut
sub set_account_email {
my ($self, $email) = @_;
unless ($email) {
undef $self->{email};
return $self->_status(OK, "Account email has been reset");
}
# Note: We don't validate email, just removing some extra bits which may be present.
$email=~s/^\s*mail(?:to):\s*//i;
$email=~s/^<([^>]+)>/$1/;
$email=~s/^\s+$//;
return $self->_status(INVALID_DATA, "Invalid email provided") unless $email;
$self->{email} = $email;
return $self->_status(OK, "Account email has been set to '$email'");
}
=head2 set_domains($domains)
Sets the list of domains to be used for verification process. This call is optional if you load or generate a CSR, in which case the list of the domains will be set at that point.
Returns: OK | INVALID_DATA.
=cut
sub set_domains {
my ($self, $domains) = @_;
my @list = @{$self->_get_list($domains)};
return $self->_status(INVALID_DATA, "No domains provided.") unless @list;
if (my $odd = $self->_verify_list(\@list)) {
return $self->_status(INVALID_DATA, "Unsupported domain names provided: " . join(", ", @{$odd}));
}
$self->{loaded_domains} = \@list;
my %loaded_domains = map {$_, undef} @list;
$self->{domains} = \%loaded_domains;
return $self->_status(OK, "Domains list is set");
}
=head2 set_version($version)
Sets the API version to be used. To pick the version automatically, use 0, other accepted values are currently 1 and 2.
Returns: OK | INVALID_DATA.
=cut
sub set_version {
my ($self, $version) = @_;
return $self->_status(INVALID_DATA, "Unsupported API version") unless (defined $version and $version=~/^\d+$/ and $version <= 2);
$self->{version} = $version;
return $self->_status(OK, "API version is set to $version.");
}
=head2 version()
Returns: The API version currently used (1 or 2). If 0 is returned, it means it is set to automatic detection and the directory has not yet been retrieved.
=cut
sub version {
my $self = shift;
return $self->{version};
}
#====================================================================================================
# API Setup helpers
#====================================================================================================
sub _reset_key {
my $self = shift;
undef $self->{$_} for qw<key_params key pem jwk fingerprint>;
}
sub _set_key {
my $self = shift;
my ($key, $msg) = @_;
my $pem = $key->get_private_key_string;
my ($n, $e) = $key->get_key_parameters;
return $self->_status(INVALID_DATA, "Key modulus is divisible by a small prime and will be rejected.") if $self->_is_divisible($n);
$key->use_sha256_hash;
$self->{key_params} = { n => $n, e => $e };
$self->{key} = $key;
$self->{pem} = $pem;
$self->{jwk} = $self->_jwk();
$self->{fingerprint} = encode_base64url(sha256($j->encode($self->{jwk})));
if ($self->{autodir}) {
my $status = $self->directory;
return $status unless ($status == OK);
}
return $self->_status(OK, $msg);
}
sub _is_divisible {
my ($self, $n) = @_;
my ($quotient, $remainder);
my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
foreach my $prime (@primes) {
($quotient, $remainder) = $n->div($prime, $ctx);
return 1 if $remainder->is_zero;
}
return 0;
}
sub _reset_csr {
my $self = shift;
undef $self->{$_} for qw<domains loaded_domains csr>;
}
sub _set_csr {
my $self = shift;
my ($csr, $pk, $domains) = @_;
$self->{csr} = $csr;
$self->{csr_key} = $pk;
my %loaded_domains = map {$_, undef} @{$domains};
$self->{loaded_domains} = $domains;
$self->{domains} = \%loaded_domains;
}
sub _get_list {
my ($self, $list) = @_;
return [ map {lc $_} (ref $list eq 'ARRAY') ? @{$list} : $list ? split /\s*,\s*/, $list : () ];
}
sub _verify_list {
my ($self, $list) = @_;
my @odd = grep { /[\s\[\{\(\<\@\>\)\}\]\/\\:]/ or /^[\d\.]+$/ or !/\./ } @{$list};
return @odd ? \@odd : undef;
}
#====================================================================================================
# API Workflow functions
#====================================================================================================
=head1 METHODS (API Workflow)
The following methods are provided for the API workflow processing. All but C<accept_challenge()> methods interact with Let's Encrypt servers.
=head2 directory([ $reload ])
Loads resource pointers from Let's Encrypt. This method needs to be called before the registration. It
will be called automatically upon account key loading/generation unless you have reset the 'autodir'
parameter when creating a new Crypt::LE instance. If any true value is provided as a parameter, reloads
the directory even if it has been already retrieved, but preserves the 'reg' value (for example to pull
another Nonce for the current session).
Returns: OK | INVALID_DATA | LOAD_ERROR.
=cut
sub directory {
my ($self, $reload) = @_;
if (!$self->{directory} or $reload) {
my ($status, $content) = $self->{dir} ? $self->_request($self->{dir}) : $self->_request("https://$self->{server}/directory");
if ($status == SUCCESS and $content and (ref $content eq 'HASH')) {
if ($content->{newAccount}) {
unless ($self->version) {
$self->set_version(2);
} elsif ($self->version() != 2) {
return $self->_status(INVALID_DATA, "Resource directory is not compatible with the version set (required v1, got v2).");
}
$self->_compat($content);
} elsif ($content->{'new-reg'}) {
unless ($self->version) {
$self->set_version(1);
} elsif ($self->version() != 1) {
return $self->_status(INVALID_DATA, "Resource directory is not compatible with the version set (required v2, got v1).");
}
} else {
return $self->_status(INVALID_DATA, "Resource directory does not contain expected fields.");
}
$content->{reg} = $self->{directory}->{reg} if ($self->{directory} and $self->{directory}->{reg});
$self->{directory} = $content;
unless ($self->{nonce}) {
if ($self->{directory}->{'newNonce'}) {
$self->_request($self->{directory}->{'newNonce'}, undef, { method => 'head' });
return $self->_status(LOAD_ERROR, "Could not retrieve the Nonce value.") unless $self->{nonce};
} else {
return $self->_status(LOAD_ERROR, "Could not retrieve the Nonce value and there is no method to request it.")
}
}
return $self->_status(OK, "Directory loaded successfully.");
} else {
return $self->_status(LOAD_ERROR, $content);
}
}
return $self->_status(OK, "Directory has been already loaded.");
}
=head2 new_nonce()
Requests a new nonce by forcing the directory reload. Picks up the value from the returned headers if it
is present (API v1.0), otherwise uses newNonce method to get it (API v2.0) if one is provided.
Returns: Nonce value or undef (if neither the value is in the headers nor newNonce method is available).
=cut
sub new_nonce {
my $self = shift;
undef $self->{nonce};
$self->directory(1);
return $self->{nonce};
}
=head2 register([$kid, $mac])
Registers an account key with Let's Encrypt. If the key is already registered, it will be handled automatically.
Accepts optional $kid (eab-kid) and $mac (eab-hmac-key) parameters - those are used for EAB (External Account Binding).
Returns: OK | ERROR.
=cut
sub register {
my ($self, $kid, $mac) = @_;
my $req = { resource => 'new-reg' };
$req->{contact} = [ "mailto:$self->{email}" ] if $self->{email};
my ($status, $content) = $self->_request($self->{directory}->{'new-reg'}, $req, { kid => $kid, mac => $mac });
$self->{directory}->{reg} = $self->{location} if $self->{location};
$self->{$_} = undef for (qw<registration_id contact_details>);
if ($status == $self->_compat_response(ALREADY_DONE)) {
$self->{new_registration} = 0;
$self->_debug("Key is already registered, reg path: $self->{directory}->{reg}.");
($status, $content) = $self->_request($self->{directory}->{'reg'}, { resource => 'reg' });
if ($status == $self->_compat_response(ACCEPTED)) {
$self->{registration_info} = $content;
if ($self->version() == 1 and $self->{links} and $self->{links}->{'terms-of-service'} and (!$content->{agreement} or ($self->{links}->{'terms-of-service'} ne $content->{agreement}))) {
$self->_debug($content->{agreement} ? "You need to accept TOS" : "TOS has changed, you may need to accept it again.");
$self->{tos_changed} = 1;
} else {
$self->{tos_changed} = 0;
}
} else {
return $self->_status(ERROR, $content);
}
} elsif ($status == CREATED) {
$self->{new_registration} = 1;
$self->{registration_info} = $content;
$self->{tos_changed} = 0;
my $tos_message = '';
if ($self->{links}->{'terms-of-service'}) {
$self->{tos_changed} = 1;
$tos_message = "You need to accept TOS at $self->{links}->{'terms-of-service'}";
}
$self->_debug("New key is now registered, reg path: $self->{directory}->{reg}. $tos_message");
} elsif ($status == BAD_REQUEST and $kid and $mac and $self->_pull_error($content)=~/not awaiting/) {
# EAB credentials were already associated with the key.
if ($self->{directory}->{reg}) {
$self->_debug("EAB credentials already associated. Account URL is: $self->{directory}->{reg}.");
} else {
return $self->_status(ERROR, "EAB credentials already associated and no EAB id was provided.");
}
} else {
return $self->_status(ERROR, $content);
}
if ($self->{registration_info} and ref $self->{registration_info} eq 'HASH') {
$self->{registration_id} = $self->{registration_info}->{id};
if ($self->{registration_info}->{contact} and (ref $self->{registration_info}->{contact} eq 'ARRAY') and @{$self->{registration_info}->{contact}}) {
$self->{contact_details} = $self->{registration_info}->{contact};
}
}
if (!$self->{registration_id} and $self->{directory}->{reg}=~/\/([^\/]+)$/) {
$self->{registration_id} = $1;
}
$self->_debug("Account ID: $self->{registration_id}") if $self->{registration_id};
return $self->_status(OK, "Registration success: TOS change status - $self->{tos_changed}, new registration flag - $self->{new_registration}.");
}
=head2 accept_tos()
Accepts Terms of Service set by Let's Encrypt.
Returns: OK | ERROR.
=cut
sub accept_tos {
my $self = shift;
return $self->_status(OK, "TOS has NOT been changed, no need to accept again.") unless $self->tos_changed;
my ($status, $content) = $self->_request($self->{directory}->{'reg'}, { resource => 'reg', agreement => $self->{links}->{'terms-of-service'} });
return ($status == $self->_compat_response(ACCEPTED)) ? $self->_status(OK, "Accepted TOS.") : $self->_status(ERROR, $content);
}
=head2 update_contacts($array_ref)
Updates contact details for your Let's Encrypt account. Accepts an array reference of contacts.
Non-prefixed contacts will be automatically prefixed with 'mailto:'.
Returns: OK | INVALID_DATA | ERROR.
=cut
sub update_contacts {
my ($self, $contacts) = @_;
return $self->_status(INVALID_DATA, "Invalid call parameters.") unless ($contacts and (ref $contacts eq 'ARRAY'));
my @set = map { /^\w+:/ ? $_ : "mailto:$_" } @{$contacts};
my ($status, $content) = $self->_request($self->{directory}->{'reg'}, { resource => 'reg', contact => \@set });
return ($status == $self->_compat_response(ACCEPTED)) ? $self->_status(OK, "Email has been updated.") : $self->_status(ERROR, $content);
}
=head2 request_challenge()
Requests challenges for domains on your CSR. On error you can call failed_domains() method, which returns an array reference to domain names for which
the challenge was not requested successfully.
Returns: OK | ERROR.
=cut
sub request_challenge {
my $self = shift;
$self->_status(ERROR, "No domains are set.") unless $self->{domains};
my ($domains_requested, %domains_failed);
# For v2.0 API the 'new-authz' is optional. However, authz set is provided via newOrder request (also utilized by request_certificate call).
# We are keeping the flow compatible with older clients, so if that call has not been specifically made (as it would in le.pl), we do
# it at the point of requesting the challenge. Note that if certificate is already valid, we will skip most of the challenge-related
# calls, but will not be returning the cert early to avoid interrupting the established flow.
if ($self->version() > 1) {
unless ($self->{authz}) {
my ($status, $content) = $self->_request($self->{directory}->{'new-cert'}, { resource => 'new-cert' });
if ($status == CREATED and $content->{'identifiers'} and $content->{'authorizations'}) {
push @{$self->{authz}}, [ $_, '' ] for @{$content->{'authorizations'}};
$self->{finalize} = $content->{'finalize'};
} else {
unless ($self->{directory}->{'new-authz'}) {
return $self->_status(ERROR, "Cannot request challenges - " . $self->_pull_error($content) . "($status).");
}
$self->_get_authz();
}
}
} else {
$self->_get_authz();
}
foreach my $authz (@{$self->{authz}}) {
$self->_debug("Requesting challenge.");
my ($status, $content) = $self->_request(@{$authz});
$domains_requested++;
if ($status == $self->_compat_response(CREATED)) {
my $valid_challenge = 0;
return $self->_status(ERROR, "Missing identifier in the authz response.") unless ($content->{identifier} and $content->{identifier}->{value});
my $domain = $content->{identifier}->{value};
$domain = "*.$domain" if $content->{wildcard};
foreach my $challenge (@{$content->{challenges}}) {
unless ($challenge and (ref $challenge eq 'HASH') and $challenge->{type} and
($challenge->{url} or $challenge->{uri}) and
($challenge->{status} or $content->{status})) {
$self->_debug("Challenge for domain $domain does not contain required fields.");
next;
}
my $type = (split '-', delete $challenge->{type})[0];
unless ($challenge->{token} and $challenge->{token}=~$url_safe) {
$self->_debug("Challenge ($type) for domain $domain is missing a valid token.");
next;
}
$valid_challenge = 1 if ($challenge->{status} eq 'valid');
$challenge->{uri} ||= $challenge->{url};
$challenge->{status} ||= $content->{status};
$self->{challenges}->{$domain}->{$type} = $challenge;
}
if ($self->{challenges} and exists $self->{challenges}->{$domain}) {
$self->_debug("Received challenges for $domain.");
$self->{domains}->{$domain} = $valid_challenge;
} else {
$self->_debug("Received no valid challenges for $domain.");
$domains_failed{$domain} = $self->_pull_error($content)||'No valid challenges';
}
} else {
# NB: In API v2.0 you don't know which domain you are receiving a challenge for - you can only rely
# on the identifier in the response. Even though in v1.0 we could associate domain name with this error,
# we treat this uniformly and return.
my $err = $self->_pull_error($content);
return $self->_status(ERROR, "Failed to receive the challenge. $err");
}
}
if (%domains_failed) {
my @failed = sort keys %domains_failed;
$self->{failed_domains} = [ \@failed ];
my $status = join "\n", map { "$_: $domains_failed{$_}" } @failed;
my $info = @failed == $domains_requested ? "All domains failed" : "Some domains failed";
return $self->_status(ERROR, "$info\n$status");
} else {
$self->{failed_domains} = [ undef ];
}
# Domains not requested with authz are considered to be already validated.
for my $domain (@{$self->{loaded_domains}}) {
unless (defined $self->{domains}->{$domain}) {
$self->{domains}->{$domain} = 1;
$self->_debug("Domain $domain does not require a challenge at this time.");
}
}
return $self->_status(OK, $domains_requested ? "Requested challenges for $domains_requested domain(s)." : "There are no domains which were not yet requested for challenges.");
}
=head2 accept_challenge($callback [, $params] [, $type])
Sets up a callback, which will be called for each non-verified domain to satisfy the requested challenge. Each callback will receive two parameters -
a hash reference with the challenge data and a hash reference of parameters optionally passed to accept_challenge(). The challenge data has the following keys:
=over 14
=item C<domain>
The domain name being processed (lower-case)
=item C<host>