aboutsummaryrefslogtreecommitdiffstats
path: root/webserver
blob: dad3d9db5d4223def44bcef646b13ca3681a7210 (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
#!/usr/bin/perl -T

#----------------------------------------------------------------------
# ACME client written with process isolation and minimal privileges in mind
# (webserver component)
# Copyright © 2015,2016 Guilhem Moulin <guilhem@fripost.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 of the License, 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 warnings;

# Usage: webserver FD
#
# fdopen(3) the file descriptor FD (corresponding to a listening
# socket), then keep accept(2)'ing connections and consider each
# connection as the verification of an ACME challenge, i.e., serve the
# requested challenge token.
#
# NOTE: one needs to chdir(2) to an appropriate ACME challenge directory
# before running this program, since challenge tokens are (on purpose)
# only looked for in the current directory.
#
# NOTE: one should run this program as an unprivileged user:group such
# as "www-data:www-data"; bind(2)'ing to a privileged port such as 80 is
# not a problem since FD can be bound as root prior to the execve(2).

use Errno qw/EINTR ENOENT/;
use Fcntl qw/O_NOFOLLOW O_RDONLY/;
use Socket qw/AF_UNIX AF_INET AF_INET6/;

# Untaint and fdopen(3) the listening socket
(shift @ARGV // die) =~ /\A(\d+)\z/ or die;
open (my $S, '+<&=', $1+0) or die "fdopen $1: $!";
my $ROOT = '/.well-known/acme-challenge';

close STDIN  or die "close: $!";
close STDOUT or die "close: $!";

sub info($$$) {
    my ($sockaddr, $msg, $req) = @_;
    $req =~ s/\r\n\z// if defined $req;

    # get a string representation of the peer's address
    my $fam = Socket::sockaddr_family($sockaddr);
    my $peer;

    if ($fam == AF_UNIX) {
        $peer = Socket::unpack_sockaddr_un($sockaddr);
    } else {
        my (undef, $ip) =
            $fam == AF_INET  ? Socket::unpack_sockaddr_in($sockaddr)  :
            $fam == AF_INET6 ? Socket::unpack_sockaddr_in6($sockaddr) :
            die;
        $peer = Socket::inet_ntop($fam, $ip);
    }

    $msg .= " from [$peer]" if defined $peer and $peer ne '';
    $msg .= ": $req"        if defined $req;

    print STDERR $msg, "\n";
}

while (1) {
    my $sockaddr = accept(my $conn, $S) or do {
        next if $! == EINTR; # try again if accept(2) was interrupted by a signal
        die "accept: $!";
    };
    my $req = $conn->getline();
    info($sockaddr, "[$$] Incoming connection", $req) if $ENV{DEBUG};
    next unless defined $req;

    if ($req !~ s/\A(GET|HEAD) (.*) HTTP\/(1\.[01])\r\n\z/$2/) {
        info($sockaddr, "Error: Bad request", $req);
        next;
    }
    my ($method, $proto) = ($1, $3);

    # Consume (and ignore) the headers
    while (defined (my $h = $conn->getline())) { last if $h eq "\r\n" };

    my ($status_line, $content_type, $content);
    if ($req =~ /\A\Q$ROOT\E\/([A-Za-z0-9_\-]+)\z/) {
        # only serve base64-encoded filenames (tokens) in the cwd
        # XXX stat(2) followed by open(2) is racy; open(2) would hang if
        # an attacker manages to replace a regular file with a FIFO
        # between the syscalls, leading to denial of service; however
        # there shouldn't be any risk of information disclosure as we're
        # not following symlinks (and the cwd is not owned by us)
        if (-f $1 and sysopen(my $fh, $1, O_NOFOLLOW|O_RDONLY)) {
            ($status_line, $content_type) = ('200 OK', 'application/jose+json');
            $content = do { local $/ = undef; $fh->getline() };
            $fh->close() or die "close: $!";
        } elsif ($! == ENOENT) { # errno from either stat(2) or open(2)
            $status_line = '404 Not Found';
        }
    }

    $conn->print( "HTTP/$proto ", ($status_line // '403 Forbidden'), "\r\n" );
    $conn->print( "Content-Type: $content_type\r\n" ) if defined $content_type;
    $conn->print( "Content-Length: ".length($content)."\r\n" ) if defined $content;
    $conn->print( "Connection: close\r\n" );
    $conn->print( "\r\n" );
    $conn->print( $content ) if defined $content and $method eq 'GET';

    $conn->close() or die "close: $!";
}