summaryrefslogtreecommitdiff
path: root/selfpublish.sh
blob: 25686a7794a22fe83a6ac7406eea294418603ba2 (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
#!/bin/sh
set -e

DEFAULT_AUTH_TYPE=ed25519
DEFAULT_UPSTREAM=d@cryptonomic.net:public_git/selfpublish.sh

force()
{
    [ "$FORCE" ]
}

in_group()
{
    local g
    for g in $(groups)
    do
        [ "$g" = "$1" ] && return
    done
    false
}

as_root()
{
    if [ "$(id -u)" = 0 ]
    then
        "$@"
    elif in_group sudo
    then
        sudo "$@"
    else
        su -c "$*"
    fi
}

apt_install()
{
    as_root apt-get install "$@"
}

dpkg_install()
{
    case "$(lsb_release -cs)" in
        buster)
            echo 'deb      http://httpredir.debian.org/debian  buster-backports  main' |
                as_root tee -a /etc/apt/sources.list.d/buster-backports.list >/dev/null ;;
    esac

    as_root $SHELL -c "set -$- +e; dpkg -i $*; apt-get -t buster-backports -f install"
}

dependencies()
{
    cat <<EOF
apache2 (>= 2.4.46)
basez
cgit
curl
fortune-mod
fortunes-min
gnupg (>= 2.2.14)
libssl1.1 (>= 1.1.1d)
openssl
ssh
EOF
}

fmt_dependencies()
{
    local outline=
    while read inline
    do
        if [ ! "$outline" ]
        then
            outline="Depends: $inline"
        elif [ $((${#outline} + ${#inline})) -ge 60 ]
        then
            printf '%s,\n' "$outline"
            outline=" $inline"
        else
            outline="$outline, $inline"
        fi
    done
    if [ "$outline" ]
    then
        printf '%s\n' "$outline"
    fi
}

control_file_file()
{
    printf 'File: %s %s\n' "$1" "$2"
    sed -e 's/^/ /'
}

SELF_VERSION='0.1'
SELF_EXECUTABLE=$(realpath "$0")
control_file()
{
    cat <<EOF
Version: ${SELF_VERSION}
Package: selfpublish-dot-sh
Description: selfpublish.sh dependency package
 This package depends on the dependencies of the
 selfpublish.sh script, and is installed by that
 script to self-satisfy those dependencies.
EOF
    dependencies | fmt_dependencies
    cat <<EOF
File: /usr/share/doc/selfpublish-dot-sh/README.Debian 644
 This gets overwritten :(
EOF
    control_file_file /usr/bin/cryptonomic 755 <<'EOF'
#!/bin/dash
set -e

DOMAIN=cryptonomic.net
DEFAULT_AUTH_TYPE=ed25519
HASH_TYPE=2

die() { echo "$0: Error: $*" >&2; exit 1; }

b16_to_b32()
{
    printf %s "$1" | basez -x -d | basez -j -l | tr -d =
}

get_domain()
{
    get_sshfp "$1"

    domain=$(printf %s.%s.%s "$sshfp_b32" "$DEFAULT_AUTH_TYPE" "$DOMAIN" | tail -c64)
}

get_sshfp()
{
    [ -f "$1" ] || return
    sshfp_b16=$(ssh-keygen -r . -f "$1" | sed -ne 's/^. IN SSHFP [0-9]* '"$HASH_TYPE"' //p') &&
        [ "$sshfp_b16" ] || die "could not determine ssh client fingerprint"
    sshfp_b32=$(b16_to_b32 "$sshfp_b16")
}

KEY_FILE=/etc/ssh/ssh_host_${DEFAULT_AUTH_TYPE}_key

if [ $# = 0 -o "$1" = hostname ]
then

    get_domain "${KEY_FILE}".pub || exit
    printf '%s\n' "$domain"

elif [ "$1" = dyndns ]
then
    set -- ssh -i "$KEY_FILE" dyndns@"$DOMAIN"

    if [ -r "$KEY_FILE" ]
    then
        "$@"
    elif sudo -n true 2>/dev/null || groups | grep '\bsudo\b'
    then
        sudo -- "$@"
    else
        su -c "$(bash -c 'printf "%q " "$@"' bash "$@")"

    fi
else
    echo "Usage: $0 [dyndns|hostname]" >&2
    exit 1
fi
EOF
    control_file_file /usr/bin/selfpublish.sh 755 < "$SELF_EXECUTABLE"
    echo
}

control_file_unchanged()
{
    (
        destdir=$(mktemp -d)
        trap 'rm -r "$destdir"' EXIT
        [ "$(dpkg-query -f '${Version}' -W selfpublish-dot-sh)" = "${SELF_VERSION}" ] || return

        dependencies > want-dependencies
        dpkg-query -f '${Depends}\n' -W selfpublish-dot-sh | sed 's/, */\n/g' | sort -u > have-dependencies
        diff -q want-dependencies have-dependencies
    )
}

equivocate()
{
    if dpkg-query -s selfpublish-dot-sh | grep -q '^Status: install ok installed' 2>/dev/null
    then
        if ! force
        then
            control_file_unchanged && return
        fi
    fi
    which equivs-build >/dev/null 2>&1 || apt_install equivs
    (
        destdir=$(mktemp -d)
        cd "$destdir"
        control_file > ./control
        # cat ./control
        equivs-build ./control >&2
        DEB=selfpublish-dot-sh_${SELF_VERSION}_all.deb
        as_root dpkg -r selfpublish-dot-sh
        dpkg_install "$DEB"
        install -m0644 "$DEB" "$DEBDEST"
    ) || exit
}

ssh_keytag_to_path_fragment()
{
        case "$1" in
                ssh-dss) echo dsa ;;
                ecdsa-sha2-nistp256) echo ecdsa ;;
                ssh-rsa|ssh-ed25519) echo ${1#ssh-} ;;
                *) return 1 ;;
        esac
}

path_fragment_to_ssh_keytag()
{
        case "$1" in
                ssh-dss|ecdsa-sha2-nistp256|ssh-rsa|ssh-ed25519) echo $1;;
                dss|rsa|ed25519) echo ssh-$1 ;;
                dsa) echo ssh-dss ;;
                ecdsa) echo ecdsa-sha2-nistp256 ;;
                *) return 1 ;;
        esac
}

get_dyndns_domain()
{
        fragment=$(ssh_keytag_to_path_fragment "$1") || return

        host_keyfile=/etc/ssh/ssh_host_${fragment}_key
        user_keyfile=$HOME/.ssh/id_${fragment}

        set -- -q dyndns@cryptonomic.net

        if [ -r "$host_keyfile" ]
        then
                set -- ssh -i "$host_keyfile" "$@"

        elif in_group sudo
        then
                set -- sudo ssh -i "$host_keyfile" "$@"

        elif [ -r "$user_keyfile" ]
        then
                set -- ssh -i "$user_keyfile" "$@"

        else
                set -- ssh "$@"
        fi

        "$@"
}

enable_apache_modules()
{
        local restart=
        for MODULE in $APACHE_MODULES
        do
                if ! [ -e /etc/apache2/mods-enabled/$MODULE.load ] &&
                   ! [ "$MODULE" = cgi -a -e /etc/apache2/mods-enabled/cgid.load ]
                then
                    a2enmod $MODULE >/dev/null
                    restart=y
                fi
        done
        if [ "$restart" ]
        then
                systemctl restart apache2
        fi
}

site_conf_template()
{
cat <<END
<MDomain $DOMAIN>
        MDContactEmail webmaster@$DOMAIN
        MDCertificateAgreement accepted
        MDRequireHttps temporary
</MDomain>
<VirtualHost *:80>
        ServerName $DOMAIN
        ServerAlias ${DOMAIN}.
        Redirect / https://$DOMAIN
</VirtualHost>

<VirtualHost *:443>
        ServerName $DOMAIN

        ServerAdmin webmaster@$DOMAIN
        SSLEngine on

        ErrorLog /srv/$DOMAIN/logs/error.log
        CustomLog /srv/$DOMAIN/logs/access.log combined

        <Location "/server-status">
                SetHandler server-status
        </Location>

        DocumentRoot /srv/$DOMAIN/public_html/
        <Directory /srv/$DOMAIN/public_html>
                Options Indexes FollowSymLinks MultiViews Includes

                IndexOrderDefault Descending Date
                IndexOptions +IgnoreCase FancyIndexing
                IndexOptions +HTMLTable SuppressDescription SuppressHTMLPreamble
                IndexStyleSheet /css/autoindex.css
                IndexIgnore /unindexed /HEADER.html /css /images

                # Using an absolute url for header
                HeaderName /HEADER.html

                XBitHack on
                AllowOverride None
                Require all granted
        </Directory>

        ScriptAlias /git "/usr/lib/cgit/cgit.cgi/"
        Alias /cgit-css "/usr/share/cgit/"

</VirtualHost>
END
}

wait_for_certificate_issuance()
{
        local f state reloaded_apache=
        f=/etc/apache2/md/domains/"$1"/md.json
        local set=$-
        set +x
        echo -n Waiting for certificate... >&2
        while true
        do
            if [ -e "$f" ] && state=$(sed -ne 's/^ *"state": *\([0-9]\+\),/\1/p' "$f")
            then
                case "$state" in
                    1)
                        if ! [ "$reloaded_apache" ]
                        then
                            as_root systemctl reload apache2
                            reloaded_apache=y
                        fi
                        ;;
                    2)
                        set -$set
                        echo '  Done waiting for certificate.' >&2
                        return
                        ;;
                esac
            fi

            sleep 1
            echo -n . >&2
        done
}

install_apache_vhost()
{
        if [ -e "$SITE_CONF" ] && ! force
        then
                return
        fi

        for DIR in $APACHE_SITE_DIRS
        do
                mkdir -p "$SITE_DIR"/"$DIR"
        done

        local tmp
        tmp=$(mktemp "$SITE_CONF".XXXXXX)

        site_conf_template > "$tmp"
        mv -T "$tmp" "$SITE_CONF" || { rm -f "$tmp"; false; }
        a2ensite "$DOMAIN" >/dev/null
}

install_self_to_site()
{
        SOURCE_BASENAME=${0##*/}
        [ -d "$SITE_DIR"/public_html ] || return
        dst=$SITE_DIR/public_html/$SOURCE_BASENAME
        src=$0
        [ -e "$src" ] || return 0
        if [ ! "$src" -ef "$dst" ]
        then
                cp -Tuv "$src" "$dst" >&2
                cp -Tuv "$src" "$dst".txt >&2
        fi
        DEB="selfpublish-dot-sh_${SELF_VERSION}_all.deb"
        if [ -e "$DEB" ]
        then
            cp -Tuv "$DEB" "$SITE_DIR/public_html/$DEB"
        fi
}

get_upstream()
{
    if [ -e selfpublish.sh -a -e .git ]
    then
        UPSTREAM=$(git config --get branch.master.remote 2>/dev/null)
    fi
    UPSTREAM=${UPSTREAM:-$DEFAULT_UPSTREAM}
    [ "$UPSTREAM" ]
}

write_cgit_config()
{
    get_upstream
    cgit_scan_dir=/srv/public_git
    if ! [ -e "$cgit_scan_dir"/selfpublish.sh ]
    then
        mkdir -p "$cgit_scan_dir"
        (cd "$cgit_scan_dir"
         git clone --bare "$UPSTREAM" selfpublish.sh)
    fi
    line="scan-path=$cgit_scan_dir"
    grep -qxF "$line" /etc/cgitrc || printf '%s\n' "$line" >> /etc/cgitrc
}

install_tls_public_certificate()
{
    local src=/etc/apache2/md/domains/"$DOMAIN"/pubcert.pem dst="$SITE_DIR"/public_html/pubcert.pem
    if [ "$src" -nt "$dst" ]
    then
        cp -Tuv /etc/apache2/md/domains/"$DOMAIN"/pubcert.pem "$SITE_DIR"/public_html/pubcert.pem
        openssl x509 -in "$dst" -noout -text > "$dst".txt
    fi
}

get_home()
{
    [ "$1" ] && getent passwd "$1" | (IFS=: read _ _ _ _ _ h _ && echo $h)
}

process_key()
{
    local uid="$1" domain="${1#*@}" destdir="$2" tdir
    while read keyid some_uid
    do
        [ "$some_uid" = "$uid" ] || continue
        tempdir=$(mktemp -d)
        /usr/lib/gnupg/gpg-wks-client --install-key -C "$tempdir" "$keyid" "$uid" 2>/dev/null
        mkdir -p "$destdir"
        mv "$tempdir"/"$domain"/hu/* -t "$destdir"
        rm -rf "$tempdir"
    done
}

install_gpg_rings()
{
    (
        domain=$DOMAIN
        dest=/srv/$domain/public_html/.well-known/openpgpkey/hu
        uid=${SUDO_USER:-$(id -un)}@$domain

        if [ "$SUDO_USER" -a ! "$GNUPGHOME" ]
        then
            GNUPGHOME=$(get_home "$SUDO_USER")/.gnupg
            export GNUPGHOME
        fi

        gpg --list-options show-only-fpr-mbox -k "$uid" 2>&- | process_key "$uid" "$dest"

        find /srv/"$DOMAIN"/public_html/.well-known/openpgpkey/ -type d -exec chmod 755 '{}' ';'

        ln -sfT .well-known/openpgpkey/hu /srv/"$domain"/public_html/openpgpkey
    )
}

configure_apache_vhost()
{
    enable_apache_modules
    install_self_to_site
    install_header_to_site
    install_tls_public_certificate
    install_gpg_rings
    write_cgit_config
}

install_header_to_site()
{
    cat > "$SITE_DIR"/public_html/HEADER.html <<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
 <head>
  <title>
    selfpublish.sh at <!--#echo var="SERVER_NAME" -->
  </title>
  <link rel="stylesheet" href="/css/autoindex.css" type="text/css">

  <style type=text/css>
    td { padding: 10px; }
    td.cmds {border: 1px solid;}

    #toggle_expand[type="checkbox"]:checked       ~ * .expand {display: "";}
    #toggle_expand[type="checkbox"]:not(:checked) ~ * .expand {display: none;}

    #main {
        text-align:left;
        margin-top: 10%;
        margin-bottom: 10%;
        font-size: 15px;
        line-height: 2em;
        border-spacing: 10px;
    }
  </style>
</head>
<body>

<input type=checkbox id=toggle_expand name=toggle_expand style='visibility: hidden' />
<table id=main>
    <tr>
        <td colspan=2 style='border: 2px solid; padding: 18px;'>
        <strong style='font-size: 20px'>selfpublish.sh</strong>
    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand>
        <strong>Install</strong>
        </label>
    <tr>
        <td>
        <td>
        <td>
        <td class=cmds> curl -OR https://<!--#echo var="SERVER_NAME" -->/selfpublish.sh && sudo bash selfpublish.sh

    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand>
        <strong>Requirements</strong>
        </label>
    <tr class=expand>
        <td>
        <td>
        <td>Distribution
        <td style='border: 1px solid; padding: 12px; text-align: center;'> <a href="https://debian.org">Debian</a> GNU/Linux
    <tr class=expand>
        <td>
        <td>
        <td>Version
        <td style='border: 1px solid; padding: 12px; text-align: center;'> <code>buster</code> or later

    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand>
        <strong>Browse source</strong>
        </label>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Local repository:
        <td class=cmds>
                <a href="git/selfpublish.sh">
                https://<!--#echo var="SERVER_NAME" -->/git/selfpublish.sh
                </a>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Upstream repository:
        <td class=cmds>
                <a href="https://git.cryptonomic.net/selfpublish.sh">
                https://git.cryptonomic.net/selfpublish.sh/
                </a>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Download single file:
        <td class=cmds>
                <a href="selfpublish.sh"> https://<!--#echo var="SERVER_NAME" -->/selfpublish.sh</a>

    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand><strong>Develop (<a href="https://git-scm.com/">git</a>)</strong></label>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right'>Clone local repository:
        <td class=cmds>
        git&nbsp;clone&nbsp;/srv/<!--#echo var="SERVER_NAME"-->/public_git/selfpublish.sh/&nbsp;&& cd&nbsp;selfpublish.sh&nbsp;&& make
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right'>Share local repository (read-only):
        <td class=cmds>
        git&nbsp;clone&nbsp;https://<!--#echo var="SERVER_NAME"-->/git/selfpublish.sh&nbsp;&& cd&nbsp;selfpublish.sh&nbsp;&& make
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>To push changes upstream:
        <td class=cmds>
                git&nbsp;clone&nbsp;d@cryptonomic.net:public_git/selfpublish.sh<br>
    </tr>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Local git repository:
        <td class=cmds>
                git&nbsp;clone&nbsp;https://<!--#echo var="SERVER_NAME"-->/git/selfpublish.sh<br>
    </tr>

</table>

<pre style=font-size:1.3em>
Fortunately,

<!--#exec cmd="/usr/games/fortune |sed 's/^/   /'" -->
</pre>
EOF
    chmod +x "$SITE_DIR"/public_html/HEADER.html
}

check_tls()
{
        curl -s -S -I https://"$1" >/dev/null
}

DEBDEST=$(realpath .)
[ "$NO_APT" ] || equivocate >&2

APACHE_MODULES='status md rewrite ssl include cgi'
APACHE_SITE_DIRS='logs public_html'


AUTH_TYPE=${1:-$DEFAULT_AUTH_TYPE}
AUTH_KEYTAG=$(path_fragment_to_ssh_keytag "$AUTH_TYPE")
DYNDNS=$(get_dyndns_domain "$AUTH_KEYTAG")
DOMAIN=${DYNDNS%% *}
SITE_DIR=/srv/$DOMAIN
SITE_CONF=/etc/apache2/sites-available/$DOMAIN.conf

case "$DOMAIN" in
    *."$AUTH_KEYTAG".cryptonomic.net) ;;
    *."$AUTH_TYPE".cryptonomic.net) ;;
    *)
        printf 'Error: %s\n' "Unexpected domain returned by server: $DOMAIN (AUTH_TYPE=$AUTH_TYPE)"
        exit 1 ;;
esac

check_tls "$DOMAIN"
tls_result=$?

install_apache_vhost
configure_apache_vhost

if [ $tls_result != 0 ] || force
then
        systemctl restart apache2
        wait_for_certificate_issuance "$DOMAIN"
        systemctl reload apache2 || systemctl restart apache2
else
        systemctl reload apache2 || systemctl restart apache2
fi

check_tls "$DOMAIN"
printf '%s\n' "https://$DOMAIN/selfpublish.sh"