#!/bin/bash

###
# autobuild apache 2.4.39 with openssl 1.1.1b for tls v1.3 (debian / ubuntu)
# (c) dominion 2019
###

apt update && apt install -y build-essential libpcre3-dev libssl1.1 libssl-dev libexpat1-dev zlib1g-dev

# pcre
cd /usr/local/src
wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz
tar xf pcre-8.43.tar.gz
cd /usr/local/src/pcre-8.43
./configure --prefix=/opt/apache2
make -j4
make install

# openssl
cd /usr/local/src
wget https://www.openssl.org/source/openssl-1.1.1b.tar.gz
tar xf openssl-1.1.1b.tar.gz
cd /usr/local/src/openssl-1.1.1b/
./config \
    --prefix=/opt/openssl \
    --openssldir=/opt/openssl
make -j4
make install

# apache
cd /usr/local/src
wget http://ftp.halifax.rwth-aachen.de/apache//httpd/httpd-2.4.39.tar.gz
wget http://us.mirrors.quenda.co/apache//apr/apr-1.7.0.tar.gz
wget http://us.mirrors.quenda.co/apache//apr/apr-util-1.6.1.tar.gz
tar xf httpd-2.4.39.tar.gz 
tar xf apr-1.7.0.tar.gz 
tar xf apr-util-1.6.1.tar.gz 
mv apr-1.7.0 httpd-2.4.39/srclib/apr
mv apr-util-1.6.1 httpd-2.4.39/srclib/apr-util
cd /usr/local/src/httpd-2.4.39
export LD_LIBRARY_PATH=/opt/openssl/lib
./configure \
    --prefix=/opt/apache2 \
    --with-included-apr \
    --enable-ssl \
    --with-ssl=/opt/openssl \
    --enable-mods-shared=all \
    --with-pcre=/opt/apache2
make -j4
make install

# activate apache modules
sed -i "
s/#LoadModule ssl_module modules\/mod_ssl.so/LoadModule ssl_module modules\/mod_ssl.so/
s/#Include conf\/extra\/httpd-ssl\.conf/Include conf\/extra\/httpd-ssl\.conf/
s/#LoadModule socache_shmcb_module modules\/mod_socache_shmcb.so/LoadModule socache_shmcb_module modules\/mod_socache_shmcb.so    /" /opt/apache2/conf/httpd.conf

# activate tls 1.3 and chacha20_poly1305 cipher
cat <<EOF >> /opt/apache2/conf/extra/httpd-ssl.conf
SSLCipherSuite      ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLCipherSuite      TLSv1.3 TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384
EOF

# generate server.crt
cd /opt/apache2/conf/
/opt/openssl/bin/openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout server.key -out server.crt -subj /CN=example.com


cat <<EOF > /etc/systemd/system/apache2.service
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
Environment=APACHE_STARTED_BY_SYSTEMD=true
Environment=LD_LIBRARY_PATH=/opt/openssl/lib
ExecStart=/opt/apache2/bin/apachectl start
ExecStop=/opt/apache2/bin/apachectl stop
ExecReload=/opt/apache2/bin/apachectl graceful
PrivateTmp=true
Restart=on-abort

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl reenable apache2.service
systemctl restart apache2.service


