aboutsummaryrefslogtreecommitdiff
path: root/acmeman
blob: bef9732d1677470f704a351d5f1174d7a1154fe1 (plain)
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
#! /usr/bin/perl
# Copyright (C) 2017 Sergey Poznyakoff <gray@gnu.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
use strict;
use feature 'state';
use Protocol::ACME;
use Protocol::ACME::Challenge::LocalFile;
use Crypt::Format;
use Crypt::OpenSSL::PKCS10 qw(:const);
use Crypt::OpenSSL::RSA;
use Crypt::OpenSSL::X509;
use File::Basename;
use File::Path qw(make_path);
use DateTime::Format::Strptime;
use LWP::UserAgent;
use LWP::Protocol::https;
use Pod::Usage;
use Pod::Man;
use Getopt::Long qw(:config gnu_getopt no_ignore_case);
use POSIX qw(strftime time floor);
use Data::Dumper;

our $VERSION = '1.03';

=head1 NAME

acmeman - manages ACME certificates

=head1 SYNOPSIS

B<acmeman>
[B<-Fadns>]
[B<-D> I<N>]
[B<-I> I<DIR>]    
[B<-f> I<FILE>]    
[B<-l> B<slackware>|B<debian>|B<rh>]
[B<--alt-names>]
[B<--config-file=>I<FILE>]
[B<--debug>]
[B<--dry-run>]
[B<--force>]
[B<--incdir=>I<DIR>]    
[B<--include-directory=>I<DIR>]    
[B<--layout=>B<slackware>|B<debian>|B<rh>]
[B<--restart=>I<COMMAND>]
[B<--stage>]    
[B<--time-delta=>I<N>]
[I<DOMAIN>...]
    
B<acmeman> B<--setup> | B<-S>
[B<-Fdn>]
[B<-f> I<FILE>]    
[B<-l> B<slackware>|B<debian>|B<rh>]
[B<--config-file=>I<FILE>]
[B<--debug>]
[B<--dry-run>]
[B<--force>]
[B<--layout=>B<slackware>|B<debian>|B<rh>]
[I<DIR>]

B<acmeman>
[B<-h>]
[B<--help>]
[B<--usage>]
    
=head1 DESCRIPTION

A tool for automatic creation and renewal of ACME (LetsEncrypt) SSL
certificates.  It assumes that HTTP is served by Apache server, version
2.4 or later (although only minor changes are necessary to make it work
with version 2.2).  Three most popular layouts of Apache configuration
files are supported: Debian, Slackware, and Red Hat.  A special
directory should be configured for receiving ACME challenges.

The package provides two Apache macros: for serving ACME challenges and
declaring SSL virtual hosts.    
    
B<Acmeman> should be started periodically, as a cronjob.  Upon startup,
it scans Apache configuration for virtual hosts using ACME certificates,
checks their expiration times, and renews those of the certificates that
are nearing their expiration times within a predefined number of seconds
(24 hours by default).  If any of the certificates were updated during
the run, B<acmeman> will restart the B<httpd> server.    

=head2 Setup    

To set up the necessary infrastructure, run B<acmeman --setup>.  It will
create the configuration file B<httpd-letsencrypt.conf>, defining two
macros for SSL-enabled sites (B<mod_macro> is needed).  Finally, it will
create the directory B</var/www/acme>, which will be used for receiving
and serving ACME challenges.  If another directory is preferred, it can
be specified as an argument to B<acmeman --setup>.

The tool will try to determine the layout of the Apache configuration
files and place the created file accordingly, so that it will be included
into the main configuration file.  It will print the name of the created
file at the end of the run.  You are advised to ensure that the file is
included and that the module B<mod_macro> is loaded prior to it.  You
may also wish to revise B<httpd-letsencrypt.conf> and edit the paths to
SSL files configured there.  By default, the directory F</etc/acme/I<DOMAIN>>
will be created for each domain name needing SSL, and two files will be placed
there: F<cert.pem>, containing the leaf and intermediate certificates for that
domain, and F<privkey.pem>, containing the private key for that domain.    

If the program is unable to determine the Apache configuration layout, you can
declare it using the B<--layout> option.  It takes a single argument, one of:
B<debian>, B<slackware>, or B<rh> (all lower case).  Alternatively, you can
specify the location of the main Apache configuration file, using the
B<--config-file> option.

The program will refuse to overwrite existing files B<httpd-letsencrypt.conf>,
unless given the B<--force> (B<-F>) option.

=head2 Configuring SSL
    
To declare that a virtual host needs SSL certificate, add the following
line to the Apache B<VirtualHost> block serving plain HTTP for that host:

    Use LetsEncryptChallenge

This will instruct B<acmeman> to request a certificate for that virtual
host.  The hostname declared with the B<ServerName> statement will be used
as the B<CN> for the certificate, and any names declared via B<ServerAlias>
statements will form the list of alternative names (obviously, wildcards are
not allowed).

If such a certificate doesn't exist, it will be requested and created when
B<acmeman> is run.

To use the created certificate, create a new B<VirtualHost> block that
contains the following statement:    

    Use LetsEncryptServer DOMAIN

where I<DOMAIN> is the name used in the B<ServerName> statement of the plain
HTTP configuration.  Copy the B<ServerAlias> statements (if any), and add the
rest of configuration statements.  Note, that you need not use the
B<ServerName> statement, as it will be included when the B<LetsEncryptServer>
macro is expanded.

Example:

    <VirtualHost *:80>
        ServerName example.org
        ServerAlias www.example.com
        Use LetsEncryptChallenge
        ...
    </VirtualHost>

    <VirtualHost *:443>
        Use LetsEncryptServer example.org
        ServerAlias www.example.com
        ...
    </VirtualHost>

Alternatively, you can use the B<LetsEncryptSSL> macro, which differs from
B<LetsEncryptServer> in that it configures only SSL settings, without the
B<ServerName> statement, which therefore must be included explicitly:    
    
    <VirtualHost *:443>
        ServerName example.org
        ServerAlias www.example.com
        Use LetsEncryptSSL example.org
        ...
    </VirtualHost>

LetsEncrypt limits the number of certificates requested for a single
registered domain per week (at the time of this writing - 20).  To avoid
hitting that limit, you may wish to use the same certificate for different
virtual hosts.  The special macro B<LetsEncryptReference> is provided for
that purpose.  Suppose, for example, that you wish to configure server
name B<git.example.org> to use the same certificate as B<example.org>
(configured in the example above).  You then declare the virtual host
for the plain HTTP as follows:    

    <VirtualHost *:80>
        ServerName git.example.org
        Use LetsEncryptReference example.org
        ...
    </VirtualHost>

The argument to the B<LetsEncryptReference> macro indicates the CN name of
the certificate to which the current server name (and aliases, if any) are
to be added as alternative names.  The corresponding virtual host for SSL
will use the B<LetsEncryptSSL> macro to configure the correct certificate:    

    <VirtualHost *:80>
        ServerName git.example.org
        Use LetsEncryptSSL example.org
        ...
    </VirtualHost>

=head1 OPTIONS

=over 4

=item B<-D>, B<--tile-delta=>I<N>

Sets the time window before the actual expiration time, when the certificate
becomes eligible for renewal.  I<N> is time in seconds.  The default
value is 86400, which means that B<acmeman> will attempt to renew any
certificate that expires within 24 hours.     
    
=item B<-F>, B<--force>

Force renewal of certificates, no matter their expire date.  With B<--setup>,
force installing the B<httpd-letsencrypt.conf> file even if it already
exists.    

=item B<-I>, B<--incdir>, B<--include-directory=>I<DIR>

Specifies base directory for Apache B<Include> and B<IncludeOptional>
statements with relative pathnames.      
    
=item B<-a>, B<--alt-names>

Compare the list of alternative names of each certificate with the one
gathered from the Apache configuration, and reissue the certificate 
if the two lists don't match.  This uses an ad-hoc logic, due to the
deficiency of the underlying X509 module, and therefore is not enabled
by default.    
    
=item B<-d>, B<--debug>

Increase debugging level.  Multiple options accumulate.  Three debugging
levels are implemented:

=over 8

=item B<-d>

List certificates being renewed.
    
=item B<-dd>

List files being created.  Show basic information about ACME transactions for
each certificate.    

=item B<-ddd>

Verbosely report parsing of Apache configuration files.  Show detailed
debugging information about ACME transactions for each certificate.    
    
=back    
    
=item B<-f>, B<--config-file=>I<FILE>

Read I<FILE> as main Apache configuration file.
    
=item B<-l>, B<--layout=>I<NAME>

Defines Apache configuration file layout.  Valid values for I<NAME> are:
B<slackware>, B<debian>, and B<rh> (for Red Hat).
    
=item B<-n>, B<--dry-run>

Don't modify any files, just print what would have been done.
Implies B<--debug>. 

=item B<--restart=>I<COMMAND>

Specifies the command to restart Apache daemon.    
    
=item B<-S>, B<--setup>

Set up the B<acmeman> infrastructure files.
    
=item B<-s>, B<--stage>
    
Use LetsEncrypt staging server.
 
=back

The following options are informational:

=over 4

=item B<-h>

Prints a short usage summary.
    
=item B<--help>

Prints detailed user manual.    

=item B<--usage>

Outputs a terse reminder of the command line syntax along with a
list of available options.

=back    
    
=head1 AUTHOR

Sergey Poznyakoff <gray@gnu.org>    
    
=cut    

my $progname = basename($0);
my $progdescr = "manages ACME certificates";
my $debug;
my $dry_run;
my $acme_host = 'prod';
my %acme_endpoint = (prod => 'acme-v01.api.letsencrypt.org',  
                     staging => 'acme-staging.api.letsencrypt.org');
my $letsencrypt_root_cert_url =
    'https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem';
my $time_delta = 86400;
my $force = 0;
my $check_alt_names = 0;
my %select;               # Hash of selected domain names 

# Variables read from the Apache configuration files
my $server_root;
my $www_root;             # Root directory for ACME challenges
my @virthost;             # List of virtual hosts using ACME certificates  
my $filename_arg;         # Name of the formal argument to the LetsEncrypServer
my %filename_pattern;     # File name pattern.
                          # Valid keys are: cert, key and chain.

my $account_key;
my $challenge;

use constant {
    EX_OK           => 0,
    EX_USAGE        => 64,
    EX_DATAERR      => 65,
    EX_NOINPUT      => 66,
    EX_SOFTWARE     => 70,
    EX_OSFILE       => 72,
    EX_CANTCREAT    => 73,
    EX_NOPERM       => 77,
    EX_CONFIG       => 78
};

sub error {
    my $msg = shift;
    local %_ = @_;
    print STDERR "$progname: " if defined($progname);
    print STDERR "$_{prefix}: " if defined($_{prefix});
        print STDERR "$msg\n"
}

sub debug {
    my $l = shift;
    error(join(' ',@_), prefix => 'DEBUG') if $debug >= $l;
}

sub abend {
    my $code = shift;
    print STDERR "$progname: " if defined($progname);
    print STDERR "@_\n";
    exit $code;
}

sub make_filename {
    my ($type, $arg) = @_;
    abend(EX_SOFTWARE, "no $type in \%filename_pattern")
	unless exists $filename_pattern{$type};
    my $res = $filename_pattern{$type};
    $res =~ s{$filename_arg}{$arg}g;
    return $res;
}

sub prep_dir {
    my $dir = dirname(shift);
    if (! -d $dir) {
	debug(3, "creating directory $dir");
	my @created = make_path("$dir", { error => \my $err } );
	if (@$err) {
	    for my $diag (@$err) {
		my ($file, $message) = %$diag;
		if ($file eq '') {
		    error($message);
		} else {
		    error("problem unlinking $file: $message");
		}
	    }
	    exit(EX_CANTCREAT);
	}
    }
}


sub debug_to_loglevel {
    my @lev = ('err', 'info', 'debug');
    return $lev[$debug > $#lev ? $#lev : $debug];
}

sub make_csr {
    my $cn = shift;
    my $req = Crypt::OpenSSL::PKCS10->new(4096);
    $req->set_subject("/CN=$cn");
    $req->add_ext(Crypt::OpenSSL::PKCS10::NID_subject_alt_name,
		  join(',', map { "DNS:$_" } @_)) if @_;
    $req->add_ext_final();
    $req->sign();
    if (exists($filename_pattern{key})) {
	my $filename = make_filename('key', $cn);
	debug(3, "writing $filename");
	prep_dir($filename);
	my $u = umask(077);
	$req->write_pem_pk($filename);
	umask($u);
    }
    return $req->get_pem_req();
}

sub save_crt {
    my $type = shift;
    my $domain = shift;

    my $filename = make_filename($type, $domain);
    debug(3, "writing $filename");
    prep_dir($filename);
    open(my $fd, '>', $filename);

    foreach my $der (@_) {
	my $pem = Crypt::Format::der2pem($der, 'CERTIFICATE');
	print $fd $pem;
	print $fd "\n";
    }
    close $fd;
}

sub domain_cert_expires {
    my $domain = shift;
    my $crt = make_filename('cert', $domain);
    if (-f $crt) {
	my $x509 = Crypt::OpenSSL::X509->new_from_file($crt);

	my $exts = $x509->extensions_by_name();
	if (exists($exts->{subjectAltName})) {
	    my $msg = $check_alt_names
		        ? 'will renew' : 'use -a to trigger renewal';
	    # FIXME: Crypt::OpenSSL::X509 returns extensions as strings,
	    # instead of as ASN.1 objects.  Until it is fixed, the
	    # following naive logic is implemented to split the string into
	    # names:
	    my $blob = $exts->{subjectAltName}->value();
	    my @missing;
	    foreach my $vh (map { lc } sort { length($b) <=> length($a) }
			         uniq($domain, @_)) {
		unless ($blob =~ s/\Q$vh\E\b//) {
		    push @missing, $vh;
		}
	    }
	    if (@missing) {
		debug(1, "$crt: the following SANs are missing: "
		      . join(', ', @missing)
		      ."; $msg");
		return 1 if $check_alt_names;
	    }
	}
	    
	my $expiry = $x509->notAfter();

	my $strp = DateTime::Format::Strptime->new(
	    pattern => '%b %d %H:%M:%S %Y %Z',
	    time_zone => 'GMT'
	);
	my $ts = $strp->parse_datetime($expiry)->epoch;
	my $now = time();
	if ($now < $ts) {
	    my $hours = floor(($ts - $now) / 3600);
	    my $in;
	    if ($hours > 24) {
		my $days = floor($hours / 24);
		$in = "in $days days";
	    } elsif ($hours == 24) {
		$in = "in one day";
	    } else {
		$in = "today";
	    }
	    debug(2, "$crt expires on $expiry, $in");
	    if ($now + $time_delta < $ts) {
		return 0;
	    } else {
		debug(2, "will renew $crt (expires on $expiry, $in)");
	    }
	} else {
	    debug(2, "will renew $crt");
	}
    }
    return 1;
}

sub register_domain_certificate {
    my $domain = shift;
    
    if ($debug) {
	my $crt = make_filename('cert', $domain);
	if (-f $crt) {
	    debug(1, "renewing $crt: CN=$domain, alternatives=@_");
	} else {
	    debug(1, "issuing $crt: CN=$domain, alternatives=@_");
	}
    }
    return 1 if $dry_run;
    
    my $acme = Protocol::ACME->new(
    	host => $acme_endpoint{$acme_host},
    	account_key => {
    	    buffer => $account_key->get_private_key_string(),
    	    format => 'PEM' },
    	loglevel => debug_to_loglevel()
    );

    eval {
	$acme->directory();
	$acme->register();
	$acme->accept_tos();

        foreach my $name ($domain, @_) {
   	    $acme->authz($name);
  	    $acme->handle_challenge($challenge);
	    $acme->check_challenge();
	    $acme->cleanup_challenge($challenge);
        }
	my $csr = make_csr($domain, @_);
        my $cert = $acme->sign({ format => 'PEM', buffer => $csr });
        my $chain = $acme->chain();
        if (exists($filename_pattern{chain})) {
            save_crt('cert', $domain, $cert);
	    save_crt('chain', $domain, $chain);
        } else {
            save_crt('cert', $domain, $cert, $chain);
        }
    };
    if ($@) {
    	if (UNIVERSAL::isa($@, 'Protocol::ACME::Exception')) {
    	    error("$domain: can't renew certificate: $@->{status}");
            if (exists($@->{error})) {
    	        error("$domain: $@->{error}{status} $@->{error}{detail}");
    	    } else {
    	        error("$domain: $@->{detail} $@->{type}");
            }
        } elsif (ref($@) == '') {
            chomp $@;
            error("$domain: failed to renew certificate: $@");
    	} else {
            error("$domain: failed to renew certificate");
            print STDERR Dumper([$@]);
    	}
        return 0;  
    }
    return 1;
}

sub dequote {
    my ($arg) = @_;
    $arg =~ s{^"(.*?)"$}{$1};
    return $arg;
}

sub uniq {
    my %h;
    map {
	if (exists($h{$_})) {
	    ()
	} else {
	    $h{$_} = 1;
	    $_
        }
    } @_; 
}

sub examine_http_config {
    my ($file) = @_;

    use constant {
	STATE_INITIAL         => 0, # Initial state
	STATE_VIRTUAL_HOST    => 1, # In VirtualHost block 
	STATE_USE_CHALLENGE   => 2, # Ditto, but challenge macro was used
	STATE_USE_REFERENCE   => 3, # Ditto, but reference macro was used
	STATE_MACRO_CHALLENGE => 4, # In LetsEncryptChallenge macro
	STATE_MACRO_SSL       => 5
    };

    state $state = STATE_INITIAL;
    
    debug(3, "reading apache configuration file \"$file\"");
    if (open(my $fd, '<', $file)) {
	my $server_name;
	my @server_aliases;
	my $reference;
	my $line;

	while (<$fd>) {
	    ++$line;
	    chomp;
	    s/^\s+//;
	    next if /^(#.*)?$/;
	    if (/^include(optional)?\s+(.+?)\s*$/i) {
		debug(3, "$file:$line: state $state: Include$1 $2");
		http_include(dequote($2), $1 ne '');
		next;
	    }

	    if ($state == STATE_INITIAL) {
		if (/^<VirtualHost/i) {
		    $state = STATE_VIRTUAL_HOST;
		    $server_name = undef;
		    @server_aliases = ();
		    $reference = undef;
		} elsif (/^ServerRoot\s+(.+)/i) {
		    $server_root = dequote($1);
		} elsif (/^<(?:(?i)Macro)\s+LetsEncryptChallenge/) {
		    $state = STATE_MACRO_CHALLENGE;
		} elsif (/^<(?:(?i)Macro)\s+LetsEncryptSSL\s+(.+?)\s*>/) {
		    $state = STATE_MACRO_SSL;
		    $filename_arg = $1;
		    $filename_arg =~ s{\$}{\\\$};
		}
	    } elsif ($state == STATE_VIRTUAL_HOST
		     || $state == STATE_USE_CHALLENGE
		     || $state == STATE_USE_REFERENCE) {
		if (m{</VirtualHost}i) {
		    unshift @server_aliases, $server_name
			if defined $server_name;
		    if (@server_aliases
			&& (!%select || exists($select{$server_name}))) {
			if ($state == STATE_USE_CHALLENGE) {
			    my @names = uniq(@server_aliases);
			    debug(3, "$file:$line: will handle @names");
			    push @virthost, \@names;
			} elsif ($state == STATE_USE_REFERENCE) {
			    my @names = uniq(@server_aliases);
			    unshift @names, $reference;
			    debug(3, "$file:$line: reference: @names");
			    push @virthost, \@names;
                        }			    
                    }			
		    $state = STATE_INITIAL;
		} elsif (/^(?:(?i)Use)\s+LetsEncryptChallenge/) {
		    if ($state == STATE_VIRTUAL_HOST) {
			$state = STATE_USE_CHALLENGE;
		    } elsif ($state == STATE_USE_CHALLENGE) {
			error("$file:$line: duplicate use of LetsEncryptChallenge");			
		    } else {
			error("$file:$line: LetsEncryptChallenge and LetsEncryptReference can't be used together");
		    }
		} elsif (/^(?:(?i)Use)\s+LetsEncryptReference\s+(.+)\s*$/) {
		    if ($state == STATE_VIRTUAL_HOST) {
			$state = STATE_USE_REFERENCE;
			$reference = $1;
		    } elsif ($state == STATE_USE_REFERENCE) {
			error("$file:$line: duplicate use of LetsEncryptReference");
		    } else {
			error("$file:$line: LetsEncryptChallenge and LetsEncryptReference can't be used together");
		    }			
		} elsif (/^(?:(?i)ServerName)\s+(\S+)/) {
		    $server_name = dequote($1);
		} elsif (/^(?:(?i)ServerAlias)\s+(.+)\s*$/) {
		    push @server_aliases,
		         map { /^\*\./ ? () : dequote($_) } split /\s+/, $1;
		}
	    } elsif ($state == STATE_MACRO_CHALLENGE) {
		if (m{^</macro}i) {
		    $state = STATE_INITIAL;
		} elsif (m{^(?:(?i)Alias)\s+/.well-known/acme-challenge\s+(.+)}) {
		    my $dir = dequote($1);
		    $dir =~ s{/.well-known/acme-challenge$}{};
		    $www_root = $dir;
		    debug(3, "ACME challenge root dir: $www_root");
		}
	    } elsif ($state == STATE_MACRO_SSL) {
		if (m{^</macro}i) {
		    $state = STATE_INITIAL;
		} elsif (/(?:(?i)SSLCertificate((?:Key)|(?:Chain))?File)\s+(.+)/) {
		    $filename_pattern{lc($1 ? $1 : 'cert')} = $2;
		}
	    }
	}
	close $fd;
    } else {
	error("can't open file \"$file\": $!");
	return 0;
    }
    return 1;	
}

sub http_include {
    my ($pattern, $optional) = @_;
    $pattern = "$server_root/$pattern" unless $pattern =~ m{^/};
    $pattern =~ s{/*$}{};
    $pattern .= '/*' if -d $pattern;
    foreach my $file (glob $pattern) {
	if ($optional && ! -e $file) {
	    debug(1, "optional include file \"$file\" doesn't exist");
	    next;
	}
	examine_http_config($file);
    }
}
# ##
my $apache_layout;

sub incdir {
    if (exists($apache_layout->{incdir})) {
	if (ref($apache_layout->{incdir}) eq 'CODE') {
	    return &{$apache_layout->{incdir}};
	} else {
	    return $apache_layout->{incdir};
	}
    }
    return dirname($apache_layout->{config});
}

sub get_root_cert {
    my $name = shift;
    prep_dir($name);

    debug(1, "downloading $letsencrypt_root_cert_url to \"$name\"");
    my $ua = LWP::UserAgent->new;
    my $response = $ua->get($letsencrypt_root_cert_url);
    if ($response->is_success) {
	open(my $fd, '>', $name)
	    or abend(EX_CANTCREAT, "can't open \"$name\" for writing: $!");
	print $fd $response->decoded_content;
	close $fd;
    } else {
	error("error downloading certificate from $letsencrypt_root_cert_url");
	abend(EX_NOINPUT, $response->status_line);
    }
}
	
sub initial_setup {
    if (defined($www_root)) {
	error("acmeman macros seem to be already installed");
	abend(EX_NOPERM, "use --force to continue") unless $force;
    }
    if ($#ARGV == -1) {
	$www_root = '/var/www/acme';
    } elsif ($#ARGV == 0) {
	$www_root = $ARGV[0];
    } else {
	abend(EX_USAGE, "too many arguments in setup mode");
    }
    my $filename = incdir() . "/httpd-letsencrypt.conf";
    if (-e $filename) {
	error("the file \"$filename\" already exists");
	abend(EX_NOPERM, "use --force to continue") unless $force;
    }
    debug(2, "writing $filename");
    unless ($dry_run) {
	prep_dir($filename);
	open(my $fd, '>', $filename)
	    or abend(EX_CANTCREAT, "can't open \"$filename\" for writing: $!");
	print $fd <<EOT;
<Macro LetsEncryptChallenge>
    Alias /.well-known/acme-challenge $www_root/.well-known/acme-challenge
    <Directory $www_root/.well-known/acme-challenge>
        Options None
        Require all granted
    </Directory>
    <IfModule mod_rewrite.c>
        RewriteEngine On
	RewriteRule /.well-known/acme-challenge - [L]
    </IfModule>
</Macro>

<Macro LetsEncryptReference \$domain>
    Use LetsEncryptChallenge
    Alias /.dummy/\$domain /dev/null
</Macro>

<Macro LetsEncryptSSL \$domain>
    SSLEngine on
    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder on
    SSLCipherSuite EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:EECDH+RC4:RSA+RC4:!MD5
    SSLCertificateFile /etc/ssl/acme/\$domain/cert.pem
    SSLCertificateKeyFile /etc/ssl/acme/\$domain/privkey.pem
    SSLCACertificateFile /etc/ssl/acme/lets-encrypt-x3-cross-signed.pem
</Macro>

<Macro LetsEncryptServer \$domain>
    ServerName \$domain
    Use LetsEncryptSSL \$domain
</Macro>

EOT
;
	close $fd;
	
	get_root_cert('/etc/ssl/acme/lets-encrypt-x3-cross-signed.pem');

	if (exists($apache_layout->{post_setup})) {
	    &{$apache_layout->{post_setup}}($filename);
	}
    }
    error("created file \"$filename\"", prefix => 'NOTE');
    error("please, enable mod_macro and make sure your Apache configuration includes this file", prefix => 'NOTE');
    exit(EX_OK);
}

sub coalesce {
    my $ref = shift;
    debug(2, "coalescing virtual hosts");
    my $i = 0;
    my @vhost;
    foreach my $ent (sort { $a->{names}[0] cmp $b->{names}[0] }
		     map { { ord => $i++, names => $_ } } @{$ref}) {
	if (@vhost && $vhost[-1]->{names}[0] eq $ent->{names}[0]) {
	    shift @{$ent->{names}};
	    push @{$vhost[-1]->{names}}, @{$ent->{names}};
	} else {
	    push @vhost, $ent;
	}
    }
    @{$ref} = map { $_->{names} } sort { $a->{ord} <=> $b->{ord} } @vhost;
}

my %apache_layout_tab = (
    slackware => { config => '/etc/httpd/httpd.conf',
		   incdir => '/etc/httpd/extra',
		   restart => '/etc/rc.d/rc.httpd restart'
    },
    debian =>    { config  => '/etc/apache2/apache2.conf',
		   incdir  => sub {
		               for my $dir ('/etc/apache2/conf-available',
					    '/etc/apache2/conf.d') {
				   return $dir if -d $dir;
			       }
			       warn 'none of the expected configuration directories found; falling back to /etc/apache2';
			       return '/etc/apache2';
		              },
		   restart => 'service apache2 restart',
		   post_setup => sub {
		                   my ($filename) = @_;
				   my $dir = dirname($filename);
				   my $name = basename($filename);
		                   if ($dir eq '/etc/apache2/conf-available') {
				       chdir('/etc/apache2/conf-enabled');
				       symlink "../conf-available/$name", $name;
				   }
		   }
    },
    rh =>        { config => '/etc/httpd/conf/httpd.conf',
		   incdir => '/etc/httpd/conf.d',
		   restart => 'service httpd restart'
    }
);

my $setup;

GetOptions("h" => sub {
                    pod2usage(-message => "$progname: $progdescr",
                              -exitstatus => EX_OK);
           },
           "help" => sub {
                    pod2usage(-exitstatus => EX_OK, -verbose => 2);
           },
           "usage" => sub {
                    pod2usage(-exitstatus => EX_OK, -verbose => 0);
           },
           "debug|d+" => \$debug,
           "dry-run|n" => \$dry_run,
	   "stage|s" => sub { $acme_host = 'staging' },
           "force|F" => \$force,
           "time-delta|D=n" => \$time_delta,
	   "layout|l=s" => sub {
	       my ($opt, $arg) = @_;
	       abend(EX_USAGE, "unknown layout: $arg")
		   unless exists $apache_layout_tab{$arg};
	       $apache_layout = $apache_layout_tab{$arg};
	   },
	   "setup|S" => \$setup,
	   "config-file|f=s" => sub {
	       $apache_layout ||= {};
	       $apache_layout->{config} = $_[1] 
	   },
	   "restart=s" => sub {
	       $apache_layout ||= {};
	       $apache_layout->{restart} = $_[1] 
	   },
	   "include-directory|incdir|I=s" => sub {
	       $apache_layout ||= {};
	       $apache_layout->{incdir} = $_[1] 
           },	       
	   "alt-names|a" => \$check_alt_names
) or exit(EX_USAGE);

++$debug if $dry_run;

unless (defined($apache_layout)) {
    while (my ($name, $layout) = each %apache_layout_tab) {
	if (-f $layout->{config}) {
	    debug(2, "assuming Apache layout \"$name\"");
	    $apache_layout = $layout;
	    last;
	}
    }
}

unless (defined($apache_layout)) {
    abend(EX_OSFILE, "no suitable apache configuration file found");
}

$server_root = dirname($apache_layout->{config});

if ($setup) {
    examine_http_config($apache_layout->{config}) or exit(EX_OSFILE);
    initial_setup
} else {
    @select{@ARGV} = (1) x @ARGV;
    examine_http_config($apache_layout->{config}) or exit(EX_OSFILE);
}
debug(1, "nothing to do") unless @virthost;
coalesce \@virthost;

# Check challenge root directory
if (defined($www_root)) {
    prep_dir("$www_root/file");
} else {
    abend(EX_CONFIG, "ACME challenge root directory not defined");
}
# Check filename patterns
abend(EX_CONFIG, "filename patterns not defined")
    unless (defined($filename_arg) && defined($filename_pattern{cert}));

$account_key = Crypt::OpenSSL::RSA->generate_key(4096);
$challenge = Protocol::ACME::Challenge::LocalFile->new({www_root => $www_root});

my $renewed = 0;
foreach my $vhost (@virthost) {
    if ($force || domain_cert_expires(@{$vhost})) {
	$renewed += register_domain_certificate(@$vhost);
    }
}
if ($renewed) {
    if ($apache_layout->{restart}) {
	debug(1, "running " . $apache_layout->{restart});
	exec($apache_layout->{restart}) unless $dry_run;
    } else {
	error("apache restart needed, but no restart command is defined; use the --restart option");
    }
}


    

Return to:

Send suggestions and report system problems to the System administrator.