]>
Raphaƫl G. Git Repositories - acme/blob - acme.pm
f657c235c6b2a1b882bce6fcee0fe0b6ee1434a0
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 https://letsencrypt.github.io/acme-spec/
31 #XXX: see http://www.rfc-editor.org/rfc/rfc7517.txt
32 #XXX: see ietf draft at https://ietf-wg-acme.github.io/acme/
33 #XXX: see javascript implementation https://github.com/diafygi/gethttpsforfree/blob/gh-pages/js/index.js
42 ACCOUNT_KEY
=> 'account.pem',
43 ACCOUNT_PUB
=> 'account.pub',
44 SERVER_KEY
=> 'server.pem',
45 REQUEST_CSR
=> 'request.der',
46 SERVER_CRT
=> 'server.crt',
52 ACME_DIR
=> 'https://acme-staging.api.letsencrypt.org/directory',
53 #ACME_DIR => 'https://acme-v01.api.letsencrypt.org/directory',
54 ACME_TERMS
=> 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf',
69 #XXX: tie to Tie::IxHash to keep a stable ordering of hash keys
78 # kty => uc(KEY_TYPE),
85 tie
(our %jwk, 'Tie::IxHash', pubkey
=> undef, jwk
=> undef, thumbprint
=> undef);
86 tie
(%{$jwk{jwk
}}, 'Tie::IxHash', alg
=> 'RS256', jwk
=> undef);
87 #XXX: strict ordering only really needed here for thumbprint sha256 digest
88 tie
(%{$jwk{jwk
}{jwk
}}, 'Tie::IxHash', e
=> undef, kty
=> uc(KEY_TYPE
), n
=> undef);
93 my ($class, $mail, @domains) = @_;
98 # Link self to package
101 # Add extra check to mail validity
102 #XXX: mxcheck fail if there is only a A record on the domain
103 my $ev = Email
::Valid-
>new(-fqdn
=> 1, -tldcheck
=> 1, -mxcheck
=> 1);
105 # Show error if check fail
106 if (! defined $ev->address($mail)) {
107 map { carp
'failed check: '.$_ if ($_debug) } $ev->details();
108 confess
'Email::Valid->address failed';
112 $self->{mail
} = $mail;
115 my $res = new Net
::DNS
::Resolver
();
122 unless (($tld) = $_ =~ m/\.(\w+)$/) {
123 confess
$_.'\'s tld extraction failed';
126 # Check if tld exists
127 unless(Net
::Domain
::TLD
::tld_exists
($tld)) {
128 confess
$tld.' tld from '.$_.' don\'t exists';
131 # Check if we get dns answer
132 #XXX: only search A type because letsencrypt don't support ipv6 (AAAA) yet
133 unless(my $rep = $res->search($_, 'A')) {
134 confess
'search A record for '.$_.' failed';
136 unless (scalar map { $_->type eq 'A' ? 1 : (); } $rep->answer) {
137 confess
'search recursively A record for '.$_.' failed';
143 @{$self->{domains
}} = @domains;
145 # Return class reference
149 # Prepare environement
152 make_path
(CERT_DIR
, KEY_DIR
, {error
=> \
my $err});
155 my ($file, $msg) = %$_;
156 carp
($file eq '' ? '' : $file.': ').$msg if ($_debug);
158 confess
'make_path failed';
162 $ua = LWP
::UserAgent-
>new;
163 $ua->agent(__PACKAGE__
.'/'.VERSION
)
169 open($_stderr, '>&STDERR') or die $!;
171 close(STDERR
) or die $!;
173 open(STDERR
, '>', '/dev/null') or die $!;
181 open(STDERR
, '>&', $_stderr) or die $!;
184 # Generate required keys
188 # Generate account and server key if required
190 # Check key existence
195 #XXX: we drop stderr here because openssl can't be quiet on this command
196 capturex
('openssl', ('genrsa', '-out', $_, KEY_SIZE
));
200 } (KEY_DIR
.DS
.ACCOUNT_KEY
, KEY_DIR
.DS
.SERVER_KEY
);
202 # Extract modulus and publicExponent jwk
203 #XXX: same here we tie to keep ordering
204 tie
(%{$self->{account
}}, 'Tie::IxHash', %jwk);
206 if (/^Modulus=([0-9A-F]+)$/) {
207 # Extract to binary from hex and convert to base64 url
208 $self->{account
}{jwk
}{jwk
}{n
} = encode_base64url
(pack("H*", $1) =~ s/^\0+//r);
209 } elsif (/^publicExponent:\s([0-9]+)\s\(0x[0-1]+\)$/) {
210 # Extract to binary from int, trim leading zeros and convert to base64 url
211 chomp ($self->{account
}{jwk
}{jwk
}{e
} = encode_base64url
(pack("N", $1) =~ s/^\0+//r));
213 } capturex
('openssl', ('rsa', '-text', '-in', KEY_DIR
.DS
.ACCOUNT_KEY
, '-noout', '-modulus'));
217 # Extract account public key
218 $self->{account
}{pubkey
} = join('', map { chomp; $_; } capturex
('openssl', ('rsa', '-in', KEY_DIR
.DS
.ACCOUNT_KEY
, '-pubout')));
223 #XXX: convert base64 to base64 url
224 $self->{account
}{thumbprint
} = (sha256_base64
(encode_json
($self->{account
}{jwk
}{jwk
})) =~ s/=+\z//r) =~ tr
[+/][-_
]r
;
227 # Generate certificate request
231 # Openssl config template
232 my $oct = File
::Temp-
>new();
234 # Load template from data
235 map { s/__EMAIL_ADDRESS__/$self->{mail}/; s/__COMMON_NAME__/$self->{domains}[0]/; print $oct $_; } <DATA
>;
240 # Append domain names
242 map { print $oct 'DNS.'.$i++.' = '.$_."\n"; } @{$self->{domains
}};
245 capturex
('openssl', ('req', '-new', '-outform', 'DER', '-key', KEY_DIR
.DS
.SERVER_KEY
, '-config', $oct->filename, '-out', CERT_DIR
.DS
.REQUEST_CSR
));
259 my $req = HTTP
::Request-
>new(GET
=> ACME_DIR
.'?'.$time);
262 my $res = $ua->request($req);
265 unless ($res->is_success) {
266 confess
'GET '.ACME_DIR
.'?'.$time.' failed: '.$res->status_line;
270 $self->{nonce
} = $res->headers->{'replay-nonce'};
272 # Merge uris in self content
273 %$self = (%$self, %{decode_json
($res->content)});
278 my ($self, $uri, $payload) = @_;
281 my $protected = encode_base64url
(encode_json
({nonce
=> $self->{nonce
}}));
284 $payload = encode_base64url
(encode_json
($payload));
287 my $stf = File
::Temp-
>new();
289 # Append protect.payload to stf
290 print $stf $protected.'.'.$payload;
295 # Generate digest of stf
296 my $signature = encode_base64url
(join('', capturex
('openssl', ('dgst', '-sha256', '-binary', '-sign', KEY_DIR
.DS
.ACCOUNT_KEY
, $stf->filename))) =~ s/^\0+//r);
299 my $req = HTTP
::Request-
>new(POST
=> $uri);
301 # Set new-reg request content
302 $req->content(encode_json
({
303 header
=> $self->{account
}{jwk
},
304 protected
=> $protected,
306 signature
=> $signature
310 my $res = $ua->request($req);
313 if (defined $res->headers->{'replay-nonce'}) {
314 $self->{nonce
} = $res->headers->{'replay-nonce'};
321 # Get uri and check content
323 my ($self, $uri, $content) = @_;
326 my $req = HTTP
::Request-
>new(GET
=> $uri);
329 my $res = $ua->request($req);
332 unless ($res->is_success) {
333 carp
'GET '.$uri.' failed: '.$res->status_line if ($_debug);
337 # Handle invalid content
338 unless($res->content =~ /^$content\s*$/) {
339 carp
'GET '.$uri.' content match failed: /^'.$content.'\s*$/ !~ '.$res->content if ($_debug);
348 #XXX: see doc at https://ietf-wg-acme.github.io/acme/#rfc.section.6.3
352 # Post new-reg request
353 #XXX: contact array may contain a tel:+33612345678 for example
354 my $res = $self->_post($self->{'new-reg'}, {resource
=> 'new-reg', contact
=> ['mailto:'.$self->{mail
}], agreement
=> ACME_TERMS
});
357 unless ($res->is_success || $res->code eq 409) {
358 confess
'POST '.$self->{'new-reg'}.' failed: '.$res->status_line;
361 # Update mail informations
362 if ($res->code eq 409) {
363 # Save registration uri
364 $self->{'reg'} = $res->headers->{location
};
367 #XXX: contact array may contain a tel:+33612345678 for example
368 $res = $self->_post($self->{'reg'}, {resource
=> 'reg', contact
=> ['mailto:'.$self->{mail
}]});
371 unless ($res->is_success) {
372 confess
'POST '.$self->{'reg'}.' failed: '.$res->status_line;
378 #TODO: implement combinations check one day
382 # Create challenges hash
383 %{$self->{challenges
}} = ();
388 # Create request for each domain
390 # Post new-authz request
391 my $res = $self->_post($self->{'new-authz'}, {resource
=> 'new-authz', identifier
=> {type
=> 'dns', value
=> $_}, existing
=> 'accept'});
394 unless ($res->is_success) {
395 confess
'POST '.$self->{'new-authz'}.' for '.$_.' failed: '.$res->status_line;
399 my $content = decode_json
($res->content);
402 unless (defined $content->{identifier
}{value
} && $content->{identifier
}{value
} eq $_) {
403 confess
'domain matching '.$content->{identifier
}{value
}.' for '.$_.' failed: '.$res->status_line;
407 unless ($content->{status
} eq 'valid' or $content->{status
} eq 'pending') {
408 confess
'POST '.$self->{'new-authz'}.' for '.$_.' failed: '.$res->status_line;
412 %{$self->{challenges
}{$_}} = (
419 http_challenge
=> undef
423 $self->{challenges
}{$_}{status
} = $content->{status
};
426 if ($content->{status
} eq 'pending') {
427 # Exctract validation data
428 foreach my $challenge (@{$content->{challenges
}}) {
429 if ($challenge->{type
} eq 'http-01') {
430 $self->{challenges
}{$_}{http_uri
} = $challenge->{uri
};
431 $self->{challenges
}{$_}{http_token
} = $challenge->{token
};
432 #} elsif ($challenge->{type} eq 'dns-01') {
433 # $self->{challenges}{$_}{dns_uri} = $challenge->{uri};
434 # $self->{challenges}{$_}{dns_token} = $challenge->{token};
438 # Check dns challenge
439 #XXX: disabled for now
440 #$self->_dnsCheck('_acme-challenge.'.$_.'.', $self->{challenges}{$_}{http_token}.'.'.$self->{account}{thumbprint});
442 # Check http challenge
443 if ($self->_httpCheck(
445 'http://'.$_.'/.well-known/acme-challenge/'.$self->{challenges
}{$_}{http_token
},
447 $self->{challenges
}{$_}{http_token
}.'.'.$self->{account
}{thumbprint
}
449 # Post challenge request
450 my $res = $self->_post($self->{challenges
}{$_}{http_uri
}, {resource
=> 'challenge', keyAuthorization
=> $self->{challenges
}{$_}{http_token
}.'.'.$self->{account
}{thumbprint
}});
453 unless ($res->is_success) {
454 confess
'POST '.$self->{challenges
}{$_}{http_uri
}.' failed: '.$res->status_line;
458 my $content = decode_json
($res->content);
461 $self->{challenges
}{$_}{status
} = $content->{status
};
463 # Add challenge uri to poll
464 #XXX: in case it is still pending
465 if ($content->{status
} eq 'pending') {
466 $self->{challenges
}{$_}{http_challenge
} = $content->{uri
};
470 $self->{challenges
}{$_}{status
} = 'invalid';
472 # Display challenge to fix
473 print STDERR
'Makes http://'.$_.'/.well-known/acme-challenge/'.$self->{challenges
}{$_}{http_token
}.' return '.$self->{challenges
}{$_}{http_token
}.'.'.$self->{account
}{thumbprint
}."\n";
476 } @{$self->{domains
}};
479 while (scalar map { $_->{status
} eq 'pending' ? 1 : (); } values %{$self->{challenges
}}) {
482 # Poll remaining pending
485 my $req = HTTP
::Request-
>new(GET
=> $self->{challenges
}{$_}{http_challenge
});
488 my $res = $ua->request($req);
491 unless ($res->is_success) {
492 carp
'GET '.$self->{challenges
}{$_}{http_challenge
}.' failed: '.$res->status_line if ($_debug);
496 my $content = decode_json
($res->content);
499 $self->{challenges
}{$_}{status
} = $content->{status
};
500 } map { $self->{challenges
}{$_}{status
} eq 'pending' ? $_ : (); } keys %{$self->{challenges
}};
503 # Stop here with remaining chanllenge
504 if (scalar map { ! defined $_->{status
} or $_->{status
} ne 'valid' ? 1 : (); } values %{$self->{challenges
}}) {
505 # Deactivate all activated domains
506 #XXX: not implemented by letsencrypt
508 # # Post deactivation request
509 # my $res = $self->_post($self->{challenges}{$_}{http_uri}, {resource => 'authz', status => 'deactivated'});
511 # unless ($res->is_success) {
512 # print Dumper($res);
513 # confess 'POST '.$self->{challenges}{$_}{http_uri}.' failed: '.$res->status_line;
515 #} map { $self->{challenges}{$_}{status} eq 'valid' ? $_ : () } keys %{$self->{challenges}};
517 # Stop here as a domain of csr list failed authorization
519 confess
'Fix the challenges for domains: '.join(', ', map { ! defined $self->{challenges
}{$_}{status
} or $self->{challenges
}{$_}{status
} ne 'valid' ? $_ : (); } keys %{$self->{challenges
}});
531 open(my $fh, '<', CERT_DIR
.DS
.REQUEST_CSR
) or die $!;
534 my $csr = encode_base64url
(join('', <$fh>) =~ s/^\0+//r);
537 close($fh) or die $!;
539 # Post certificate request
540 my $res = $self->_post($self->{'new-cert'}, {resource
=> 'new-cert', csr
=> $csr});
543 unless ($res->is_success) {
545 confess
'POST '.$self->{'new-cert'}.' failed: '.$res->status_line;
549 open($fh, '>', CERT_DIR
.DS
.SERVER_CRT
) or die $!;
551 print $fh '-----BEGIN CERTIFICATE-----'."\n".encode_base64
($res->content).'-----END CERTIFICATE-----'."\n";
552 #TODO: merge https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem here
554 close($fh) or die $!;
557 carp
'Success, pem certificate in '.CERT_DIR
.DS
.SERVER_CRT
if ($_debug);
560 # Resolve dns and check content
561 #XXX: this can't work without a plugin in dns to generate signature from token.thumbprint and store it in zone
562 #XXX: each identifier authorisation generate a new token, it's not possible to do a yescard answer
563 #XXX: the digest can be bigger than 255 TXT record limit and well known dns server will randomize TXT record order
565 #XXX: conclusion disabled for now
567 my ($self, $domain, $content) = @_;
570 my $stf = File
::Temp-
>new();
572 # Append protect.payload to stf
578 # Generate digest of stf
579 my $signature = encode_base64url
(join('', capturex
('openssl', ('dgst', '-sha256', '-binary', '-sign', KEY_DIR
.DS
.ACCOUNT_KEY
, $stf->filename))));
582 my $res = new Net
::DNS
::Resolver
();
584 # Check if we get dns answer
585 unless(my $rep = $res->search($domain, 'TXT')) {
586 carp
'search TXT record for '.$domain.' failed' if ($_debug);
589 unless (scalar map { $_->type eq 'TXT' && $_->txtdata =~ /^$signature$/ ? 1 : (); } $rep->answer) {
590 carp
'search recursively TXT record for '.$_.' failed' if ($_debug);
602 # OpenSSL configuration file.
603 # This is mostly being used for generation of certificate requests.
610 distinguished_name
= req_distinguished_name
611 # The extentions to add to the self signed cert
612 x509_extensions
= v3_ca
613 # The extensions to add to a certificate request
614 req_extensions
= v3_req
616 # This sets a mask for permitted string types. There are several options.
617 # utf8only: only UTF8Strings (PKIX recommendation after 2004).
618 # WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
619 string_mask
= utf8only
621 [ req_distinguished_name
]
623 stateOrProvinceName
= State
or Province Name
624 localityName
= Locality Name
625 organizationName
= Organization Name
626 organizationalUnitName
= Organizational Unit Name
627 commonName
= __COMMON_NAME__
628 emailAddress
= __EMAIL_ADDRESS__
631 basicConstraints
= CA
:false
632 keyUsage
= nonRepudiation
, digitalSignature
, keyEncipherment
633 subjectAltName
= email
:move
634 subjectAltName
= @alt_names
637 subjectKeyIdentifier
= hash
638 authorityKeyIdentifier
= keyid
:always
,issuer
639 basicConstraints
= CA
:true