summaryrefslogtreecommitdiffabout
path: root/lib/App/Acmeman/Source/Apache.pm
blob: b429f8903ea2a3a733b1fd952f39d04b36432ad7 (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
package App::Acmeman::Source::Apache;

use strict;
use warnings;
use Carp;
use feature 'state';
use File::Path qw(make_path);
use File::Spec;
use IPC::Open3;
use App::Acmeman::Apache::Layout;
use parent 'App::Acmeman::Source';
use Getopt::Long qw(GetOptionsFromArray :config gnu_getopt no_ignore_case);

sub new {
    my $class = shift;
    my $server_root;
    GetOptionsFromArray(\@_,
			'server-root=s' => \$server_root);
    my $self = bless { _layout => new App::Acmeman::Apache::Layout(@_) }, $class;
    $self->server_root($server_root) if $server_root;
    return $self;
}

sub layout { shift->{_layout} }

sub scan {
    my ($self) = @_;
    $self->debug(2, 'assuming Apache layout "'.$self->layout->name.'"');
    $self->set(qw(core postrenew), $self->layout->restart_command);
    return $self->examine_http_config($self->layout->config_file);
}

sub dequote {
    my ($self, $arg) = @_;
    $arg =~ s{^"(.*?)"$}{$1};
    return $arg;
}

sub examine_http_config {
    my ($self, $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;
    
    $self->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) {
		#$self->debug(3, "$file:$line: state $state: Include".($1||'')." $2");
		$self->http_include($self->dequote($2), defined($1));
		next;
	    }

	    if ($state == STATE_INITIAL) {
		if (/^<VirtualHost/i) {
		    $state = STATE_VIRTUAL_HOST;
		    $server_name = undef;
		    @server_aliases = ();
		    $reference = undef;
		} elsif (/^ServerRoot\s+(.+)/i) {
		    $self->server_root($self->dequote($1));
		} elsif (/^<(?:(?i)Macro)\s+LetsEncryptChallenge/) {
		    $state = STATE_MACRO_CHALLENGE;
		} elsif (/^<(?:(?i)Macro)\s+LetsEncryptSSL\s+(.+?)\s*>/) {
		    $state = STATE_MACRO_SSL;
		    $self->set(qw(files apache argument), $1);
		}
	    } 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) {
			if ($state == STATE_USE_CHALLENGE) {
			    my $cn = shift @server_aliases;
			    $self->define_domain($cn);
			    $self->define_alias($cn, @server_aliases);
			    $self->debug(3, "$file:$line: will handle ".
					 join(',', $cn, @server_aliases));
			} elsif ($state == STATE_USE_REFERENCE) {
			    $self->set('domain', $reference,
				       'files', 'apache');
			    $self->define_alias($reference, @server_aliases);
                        }			    
                    }			
		    $state = STATE_INITIAL;
		} elsif (/^(?:(?i)Use)\s+LetsEncryptChallenge/) {
		    if ($state == STATE_VIRTUAL_HOST) {
			$state = STATE_USE_CHALLENGE;
		    } elsif ($state == STATE_USE_CHALLENGE) {
			$self->error("$file:$line: duplicate use of LetsEncryptChallenge");			
		    } else {
			$self->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) {
			$self->error("$file:$line: duplicate use of LetsEncryptReference");
		    } else {
			$self->error("$file:$line: LetsEncryptChallenge and LetsEncryptReference can't be used together");
		    }			
		} elsif (/^(?:(?i)ServerName)\s+(\S+)/) {
		    $server_name = $self->dequote($1);
		} elsif (/^(?:(?i)ServerAlias)\s+(.+)\s*$/) {
		    push @server_aliases,
		         map { /^\*\./ ? () : $self->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 = $self->dequote($1);
		    $dir =~ s{/.well-known/acme-challenge$}{};
		    $self->set(qw(core rootdir), $dir);
		    $self->debug(3, "ACME challenge root dir: $dir");
		}
	    } elsif ($state == STATE_MACRO_SSL) {
		if (m{^</macro}i) {
		    $state = STATE_INITIAL;
		} elsif (/(?:(?i)SSLCertificate((?:Key)|(?:Chain))?File)\s+(.+)/) {
		    my %t = (
			'' => 'certificate-file',
			key => 'key-file',
			chain => 'ca-file'
  		    );
		    $self->set(qw(files apache), $t{lc($1||'')}, $2);
		}
	    }
	}
	close $fd;
    } else {
	$self->error("can't open file \"$file\": $!");
	return 0;
    }
    return 1;	
}

sub server_root {
    my $self = shift;
    if (my $v = shift) {
	croak "too many arguments" if $@;
	$self->{_server_root} = $v;
    }
    return $self->{_server_root};
}

sub http_include {
    my ($self, $pattern, $optional) = @_;

    unless ($self->server_root) {
	$self->probe;
    }
    
    $pattern = File::Spec->catfile($self->{_server_root}, $pattern)
	unless $pattern =~ m{^/};
    $pattern = File::Spec->catfile($pattern, '*') if -d $pattern;
    foreach my $file (glob $pattern) {
	if ($optional && ! -e $file) {
	    $self->debug(1, "optional include file \"$file\" doesn't exist");
	    next;
	}
	$self->examine_http_config($file);
    }
}

sub mkpath {
    my ($self, $dir) = @_;
    my @created = make_path("$dir", { error => \my $err } );
    if (@$err) {
	for my $diag (@$err) {
	    my ($file, $message) = %$diag;
	    if ($file eq '') {
		$self->error($message);
	    } else {
		$self->error("mkdir $file: $message");
	    }
	}
	return 0;
    }
    return 1;
}

sub setup {
    my ($self, %args) = @_;
    my $filename = $self->layout->incdir() . "/httpd-letsencrypt.conf";
    if (-e $filename) {
	if ($args{force}) {
	    ::error("the file \"$filename\" already exists",
		    prefix => 'warning');
	} else {
	    ::error("the file \"$filename\" already exists");
	    ::error("use --force to continue");
	    return 0;
	}
    }
    my $www_root = $self->get(qw(core rootdir));
    $self->debug(2, "writing $filename");
    unless ($args{dry_run}) {
	unless ($self->mkpath($self->layout->incdir())) {
	    return 0;
	}
	open(my $fd, '>', $filename)
	    or croak "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 ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:!DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA
    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;
	
	if (exists($self->{_post_setup})) {
	    &{$self->{_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');
    
    return 1;
}

sub probe {
    my ($self, @servlist) = @_;
    @servlist = qw(/usr/sbin/apachectl /usr/sbin/httpd /usr/sbin/apache2)
	unless (@servlist);
    open(my $nullout, '>', File::Spec->devnull);
    open(my $nullin, '<', File::Spec->devnull);
    foreach my $serv (@servlist) {
	use Symbol 'gensym';
	my $fd = gensym;
	eval {
	    if (my $pid = open3($nullin, $fd, $nullout, $serv, '-V')) {
		while (<$fd>) {
		    chomp;
		    if (/^\s+-D\s+HTTPD_ROOT=(.+)\s*$/) {
			$self->server_root($self->dequote($1));
			last;
		    }
		}
	    }
	};
	close $fd;
        last unless ($@)
    }
    close $nullin;
    close $nullout;
    unless ($self->server_root) {
	::error("can't deduce server root directory");
	::error("use `source = apache --server-root=DIR' in [core] section of /etc/acmeman.conf to declare it");
	exit(1);
    }
}


1;

Return to:

Send suggestions and report system problems to the System administrator.