]>
Raphaƫl G. Git Repositories - acme/blob - acme.pm
06bcac97152abd41c900e8f8d7a82e5769b56c17
10 our @ISA = qw(Exporter);
13 use Carp
qw(carp confess);
14 use Digest
::SHA
qw(sha256_base64);
16 use File
::Path
qw(make_path);
17 use File
::Temp
; # qw( :seekable );
18 use IPC
::System
::Simple
qw(capturex);
19 use JSON
qw(encode_json decode_json);
21 use MIME
::Base64
qw(encode_base64url encode_base64);
24 use POSIX
qw(EXIT_FAILURE);
30 #XXX: see ietf draft at https://ietf-wg-acme.github.io/acme/
31 #XXX: see javascript implementation https://github.com/diafygi/gethttpsforfree/blob/gh-pages/js/index.js
40 ACCOUNT_KEY
=> 'account.pem',
41 ACCOUNT_PUB
=> 'account.pub',
42 SERVER_KEY
=> 'server.pem',
43 REQUEST_CSR
=> 'request.der',
44 SERVER_CRT
=> 'server.crt',
50 ACME_DIR
=> 'https://acme-staging.api.letsencrypt.org/directory',
51 #ACME_DIR => 'https://acme-v01.api.letsencrypt.org/directory',
52 ACME_TERMS
=> 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf',
67 #XXX: tie to Tie::IxHash to keep a stable ordering of hash keys
76 # kty => uc(KEY_TYPE),
83 tie
(our %jwk, 'Tie::IxHash', pubkey
=> undef, jwk
=> undef, thumbprint
=> undef);
84 tie
(%{$jwk{jwk
}}, 'Tie::IxHash', alg
=> 'RS256', jwk
=> undef);
85 #XXX: strict ordering only really needed here for thumbprint sha256 digest
86 tie
(%{$jwk{jwk
}{jwk
}}, 'Tie::IxHash', e
=> undef, kty
=> uc(KEY_TYPE
), n
=> undef);
91 my ($class, $mail, @domains) = @_;
96 # Link self to package
99 # Add extra check to mail validity
100 #XXX: mxcheck fail if there is only a A record on the domain
101 my $ev = Email
::Valid-
>new(-fqdn
=> 1, -tldcheck
=> 1, -mxcheck
=> 1);
103 # Show error if check fail
104 if (! defined $ev->address($mail)) {
105 map { carp
'failed check: '.$_ if ($_debug) } $ev->details();
106 confess
'Email::Valid->address failed';
110 $self->{mail
} = $mail;
113 my $res = new Net
::DNS
::Resolver
();
120 unless (($tld) = $_ =~ m/\.(\w+)$/) {
121 confess
$_.'\'s tld extraction failed';
124 # Check if tld exists
125 unless(Net
::Domain
::TLD
::tld_exists
($tld)) {
126 confess
$tld.' tld from '.$_.' don\'t exists';
129 # Check if we get dns answer
130 #XXX: only search A type because letsencrypt don't support ipv6 (AAAA) yet
131 unless(my $rep = $res->search($_, 'A')) {
132 confess
'search A record for '.$_.' failed';
134 unless (scalar map { $_->type eq 'A' ? 1 : (); } $rep->answer) {
135 confess
'search recursively A record for '.$_.' failed';
141 @{$self->{domains
}} = @domains;
143 # Return class reference
147 # Prepare environement
150 make_path
(CERT_DIR
, KEY_DIR
, {error
=> \
my $err});
153 my ($file, $msg) = %$_;
154 carp
($file eq '' ? '' : $file.': ').$msg if ($_debug);
156 confess
'make_path failed';
160 $ua = LWP
::UserAgent-
>new;
161 $ua->agent(__PACKAGE__
.'/'.VERSION
)
167 open($_stderr, '>&STDERR') or die $!;
169 close(STDERR
) or die $!;
171 open(STDERR
, '>', '/dev/null') or die $!;
179 open(STDERR
, '>&', $_stderr) or die $!;
182 # Generate required keys
186 # Generate account and server key if required
188 # Check key existence
193 #XXX: we drop stderr here because openssl can't be quiet on this command
194 capturex
('openssl', ('genrsa', '-out', $_, KEY_SIZE
));
198 } (KEY_DIR
.DS
.ACCOUNT_KEY
, KEY_DIR
.DS
.SERVER_KEY
);
200 # Extract modulus and publicExponent jwk
201 #XXX: same here we tie to keep ordering
202 tie
(%{$self->{account
}}, 'Tie::IxHash', %jwk);
204 if (/^Modulus=([0-9A-F]+)$/) {
205 # Extract to binary from hex and convert to base64 url
206 $self->{account
}{jwk
}{jwk
}{n
} = encode_base64url
(pack("H*", $1) =~ s/^\0+//r);
207 } elsif (/^publicExponent:\s([0-9]+)\s\(0x[0-1]+\)$/) {
208 # Extract to binary from int, trim leading zeros and convert to base64 url
209 chomp ($self->{account
}{jwk
}{jwk
}{e
} = encode_base64url
(pack("N", $1) =~ s/^\0+//r));
211 } capturex
('openssl', ('rsa', '-text', '-in', KEY_DIR
.DS
.ACCOUNT_KEY
, '-noout', '-modulus'));
215 # Extract account public key
216 $self->{account
}{pubkey
} = join('', map { chomp; $_; } capturex
('openssl', ('rsa', '-in', KEY_DIR
.DS
.ACCOUNT_KEY
, '-pubout')));
221 #XXX: convert base64 to base64 url
222 $self->{account
}{thumbprint
} = (sha256_base64
(encode_json
($self->{account
}{jwk
}{jwk
})) =~ s/=+\z//r) =~ tr
[+/][-_
]r
;
225 # Generate certificate request
229 # Openssl config template
230 my $oct = File
::Temp-
>new();
232 # Load template from data
233 map { s/__EMAIL_ADDRESS__/$self->{mail}/; s/__COMMON_NAME__/$self->{domains}[0]/; print $oct $_; } <DATA
>;
238 # Append domain names
240 map { print $oct 'DNS.'.$i++.' = '.$_."\n"; } @{$self->{domains
}};
243 capturex
('openssl', ('req', '-new', '-outform', 'DER', '-key', KEY_DIR
.DS
.SERVER_KEY
, '-config', $oct->filename, '-out', CERT_DIR
.DS
.REQUEST_CSR
));
257 my $req = HTTP
::Request-
>new(GET
=> ACME_DIR
.'?'.$time);
260 my $res = $ua->request($req);
263 unless ($res->is_success) {
264 confess
'GET '.ACME_DIR
.'?'.$time.' failed: '.$res->status_line;
268 $self->{nonce
} = $res->headers->{'replay-nonce'};
270 # Merge uris in self content
271 %$self = (%$self, %{decode_json
($res->content)});
276 my ($self, $uri, $payload) = @_;
279 my $protected = encode_base64url
(encode_json
({nonce
=> $self->{nonce
}}));
282 $payload = encode_base64url
(encode_json
($payload));
285 my $stf = File
::Temp-
>new();
287 # Append protect.payload to stf
288 print $stf $protected.'.'.$payload;
293 # Generate digest of stf
294 my $signature = encode_base64url
(join('', capturex
('openssl', ('dgst', '-sha256', '-binary', '-sign', KEY_DIR
.DS
.ACCOUNT_KEY
, $stf->filename))) =~ s/^\0+//r);
297 my $req = HTTP
::Request-
>new(POST
=> $uri);
299 # Set new-reg request content
300 $req->content(encode_json
({
301 header
=> $self->{account
}{jwk
},
302 protected
=> $protected,
304 signature
=> $signature
308 my $res = $ua->request($req);
311 if (defined $res->headers->{'replay-nonce'}) {
312 $self->{nonce
} = $res->headers->{'replay-nonce'};
319 # Get uri and check content
321 my ($self, $uri, $content) = @_;
324 my $req = HTTP
::Request-
>new(GET
=> $uri);
327 my $res = $ua->request($req);
330 unless ($res->is_success) {
331 carp
'GET '.$uri.' failed: '.$res->status_line if ($_debug);
335 # Handle invalid content
336 unless($res->content =~ /^$content\s*$/) {
337 carp
'GET '.$uri.' content match failed: /^'.$content.'\s*$/ !~ '.$res->content if ($_debug);
346 #XXX: see doc at https://ietf-wg-acme.github.io/acme/#rfc.section.6.3
350 # Post new-reg request
351 #XXX: contact array may contain a tel:+33612345678 for example
352 my $res = $self->_post($self->{'new-reg'}, {resource
=> 'new-reg', contact
=> ['mailto:'.$self->{mail
}], agreement
=> ACME_TERMS
});
355 unless ($res->is_success || $res->code eq 409) {
356 confess
'POST '.$self->{'new-reg'}.' failed: '.$res->status_line;
359 # Update mail informations
360 if ($res->code eq 409) {
361 # Save registration uri
362 $self->{'reg'} = $res->headers->{location
};
365 #XXX: contact array may contain a tel:+33612345678 for example
366 $res = $self->_post($self->{'reg'}, {resource
=> 'reg', contact
=> ['mailto:'.$self->{mail
}]});
369 unless ($res->is_success) {
370 confess
'POST '.$self->{'reg'}.' failed: '.$res->status_line;
376 #TODO: implement combinations check one day
380 # Create challenges hash
381 %{$self->{challenges
}} = ();
386 # Create request for each domain
388 # Post new-authz request
389 my $res = $self->_post($self->{'new-authz'}, {resource
=> 'new-authz', identifier
=> {type
=> 'dns', value
=> $_}, existing
=> 'accept'});
392 unless ($res->is_success) {
393 confess
'POST '.$self->{'new-authz'}.' for '.$_.' failed: '.$res->status_line;
397 my $content = decode_json
($res->content);
400 unless (defined $content->{identifier
}{value
} && $content->{identifier
}{value
} eq $_) {
401 confess
'domain matching '.$content->{identifier
}{value
}.' for '.$_.' failed: '.$res->status_line;
405 unless ($content->{status
} eq 'valid' or $content->{status
} eq 'pending') {
406 confess
'POST '.$self->{'new-authz'}.' for '.$_.' failed: '.$res->status_line;
410 %{$self->{challenges
}{$_}} = (
417 http_challenge
=> undef
421 $self->{challenges
}{$_}{status
} = $content->{status
};
424 if ($content->{status
} eq 'pending') {
425 # Exctract validation data
426 foreach my $challenge (@{$content->{challenges
}}) {
427 if ($challenge->{type
} eq 'http-01') {
428 $self->{challenges
}{$_}{http_uri
} = $challenge->{uri
};
429 $self->{challenges
}{$_}{http_token
} = $challenge->{token
};
430 #} elsif ($challenge->{type} eq 'dns-01') {
431 # $self->{challenges}{$_}{dns_uri} = $challenge->{uri};
432 # $self->{challenges}{$_}{dns_token} = $challenge->{token};
436 # Check dns challenge
437 #XXX: disabled for now
438 #$self->_dnsCheck('_acme-challenge.'.$_.'.', $self->{challenges}{$_}{http_token}.'.'.$self->{account}{thumbprint});
440 # Check http challenge
441 if ($self->_httpCheck(
443 'http://'.$_.'/.well-known/acme-challenge/'.$self->{challenges
}{$_}{http_token
},
445 $self->{challenges
}{$_}{http_token
}.'.'.$self->{account
}{thumbprint
}
447 # Post challenge request
448 my $res = $self->_post($self->{challenges
}{$_}{http_uri
}, {resource
=> 'challenge', keyAuthorization
=> $self->{challenges
}{$_}{http_token
}.'.'.$self->{account
}{thumbprint
}});
451 unless ($res->is_success) {
452 confess
'POST '.$self->{challenges
}{$_}{http_uri
}.' failed: '.$res->status_line;
456 my $content = decode_json
($res->content);
459 $self->{challenges
}{$_}{status
} = $content->{status
};
461 # Add challenge uri to poll
462 #XXX: in case it is still pending
463 if ($content->{status
} eq 'pending') {
464 $self->{challenges
}{$_}{http_challenge
} = $content->{uri
};
468 $self->{challenges
}{$_}{status
} = 'invalid';
470 # Display challenge to fix
471 print STDERR
'Makes http://'.$_.'/.well-known/acme-challenge/'.$self->{challenges
}{$_}{http_token
}.' return '.$self->{challenges
}{$_}{http_token
}.'.'.$self->{account
}{thumbprint
}."\n";
474 } @{$self->{domains
}};
477 while (scalar map { $_->{status
} eq 'pending' ? 1 : (); } values %{$self->{challenges
}}) {
480 # Poll remaining pending
483 my $req = HTTP
::Request-
>new(GET
=> $self->{challenges
}{$_}{http_challenge
});
486 my $res = $ua->request($req);
489 unless ($res->is_success) {
490 carp
'GET '.$self->{challenges
}{$_}{http_challenge
}.' failed: '.$res->status_line if ($_debug);
494 my $content = decode_json
($res->content);
497 $self->{challenges
}{$_}{status
} = $content->{status
};
498 } map { $self->{challenges
}{$_}{status
} eq 'pending' ? $_ : (); } keys %{$self->{challenges
}};
501 # Stop here with remaining chanllenge
502 if (scalar map { ! defined $_->{status
} or $_->{status
} ne 'valid' ? 1 : (); } values %{$self->{challenges
}}) {
503 # Deactivate all activated domains
504 #XXX: not implemented by letsencrypt
506 # # Post deactivation request
507 # my $res = $self->_post($self->{challenges}{$_}{http_uri}, {resource => 'authz', status => 'deactivated'});
509 # unless ($res->is_success) {
510 # print Dumper($res);
511 # confess 'POST '.$self->{challenges}{$_}{http_uri}.' failed: '.$res->status_line;
513 #} map { $self->{challenges}{$_}{status} eq 'valid' ? $_ : () } keys %{$self->{challenges}};
515 # Stop here as a domain of csr list failed authorization
517 confess
'Fix the challenges for domains: '.join(', ', map { ! defined $self->{challenges
}{$_}{status
} or $self->{challenges
}{$_}{status
} ne 'valid' ? $_ : (); } keys %{$self->{challenges
}});
529 open(my $fh, '<', CERT_DIR
.DS
.REQUEST_CSR
) or die $!;
532 my $csr = encode_base64url
(join('', <$fh>) =~ s/^\0+//r);
535 close($fh) or die $!;
537 # Post certificate request
538 my $res = $self->_post($self->{'new-cert'}, {resource
=> 'new-cert', csr
=> $csr});
541 unless ($res->is_success) {
543 confess
'POST '.$self->{'new-cert'}.' failed: '.$res->status_line;
547 open($fh, '>', CERT_DIR
.DS
.SERVER_CRT
) or die $!;
549 print $fh '-----BEGIN CERTIFICATE-----'."\n".encode_base64
($res->content).'-----END CERTIFICATE-----'."\n";
550 #TODO: merge https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem here
552 close($fh) or die $!;
555 carp
'Success, pem certificate in '.CERT_DIR
.DS
.SERVER_CRT
if ($_debug);
558 # Resolve dns and check content
559 #XXX: this can't work without a plugin in dns to generate signature from token.thumbprint and store it in zone
560 #XXX: each identifier authorisation generate a new token, it's not possible to do a yescard answer
561 #XXX: the digest can be bigger than 255 TXT record limit and well known dns server will randomize TXT record order
563 #XXX: conclusion disabled for now
565 my ($self, $domain, $content) = @_;
568 my $stf = File
::Temp-
>new();
570 # Append protect.payload to stf
576 # Generate digest of stf
577 my $signature = encode_base64url
(join('', capturex
('openssl', ('dgst', '-sha256', '-binary', '-sign', KEY_DIR
.DS
.ACCOUNT_KEY
, $stf->filename))));
580 my $res = new Net
::DNS
::Resolver
();
582 # Check if we get dns answer
583 unless(my $rep = $res->search($domain, 'TXT')) {
584 carp
'search TXT record for '.$domain.' failed' if ($_debug);
587 unless (scalar map { $_->type eq 'TXT' && $_->txtdata =~ /^$signature$/ ? 1 : (); } $rep->answer) {
588 carp
'search recursively TXT record for '.$_.' failed' if ($_debug);
600 # OpenSSL configuration file.
601 # This is mostly being used for generation of certificate requests.
608 distinguished_name
= req_distinguished_name
609 # The extentions to add to the self signed cert
610 x509_extensions
= v3_ca
611 # The extensions to add to a certificate request
612 req_extensions
= v3_req
614 # This sets a mask for permitted string types. There are several options.
615 # utf8only: only UTF8Strings (PKIX recommendation after 2004).
616 # WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
617 string_mask
= utf8only
619 [ req_distinguished_name
]
621 stateOrProvinceName
= State
or Province Name
622 localityName
= Locality Name
623 organizationName
= Organization Name
624 organizationalUnitName
= Organizational Unit Name
625 commonName
= __COMMON_NAME__
626 emailAddress
= __EMAIL_ADDRESS__
629 basicConstraints
= CA
:false
630 keyUsage
= nonRepudiation
, digitalSignature
, keyEncipherment
631 subjectAltName
= email
:move
632 subjectAltName
= @alt_names
635 subjectKeyIdentifier
= hash
636 authorityKeyIdentifier
= keyid
:always
,issuer
637 basicConstraints
= CA
:true