# Install Modsecurity in a Docker container
FROM ubuntu:20.04 as production
ARG DEBIAN_FRONTEND=noninteractive

# update/upgrade your system
# Install Required Dependencies
RUN apt-get update && apt-get install -y \
	g++ flex bison curl apache2-dev \
	doxygen libyajl-dev ssdeep liblua5.2-dev \
	libgeoip-dev libtool dh-autoreconf \
	libcurl4-gnutls-dev libxml2 libpcre++-dev \
	libxml2-dev git wget tar apache2 \
    && rm -rf /var/lib/apt/lists/*

# Download LibModsecurity. Extract the Downloaded File. Compile and Install LibModsecurity
RUN wget https://github.com/SpiderLabs/ModSecurity/releases/download/v3.0.8/modsecurity-v3.0.8.tar.gz \
	&& tar xzf modsecurity-v3.0.8.tar.gz && rm -rf modsecurity-v3.0.8.tar.gz \
	&& cd modsecurity-v3.0.8 && \
	./build.sh && ./configure && \
	make && make install

# Install ModSecurity-Apache Connector
RUN cd ~ && git clone https://github.com/SpiderLabs/ModSecurity-apache \
	&& cd ~/ModSecurity-apache && \
	./autogen.sh && \
	./configure --with-libmodsecurity=/usr/local/modsecurity/ && \
	make && \
	make install

# logs should go to stdout / stderr
RUN set -ex \
	&& ln -sfT /dev/stderr /var/log/apache2/error.log \
	&& ln -sfT /dev/stdout /var/log/apache2/access.log \
	&& ln -sfT /dev/stdout /var/log/apache2/other_vhosts_access.log

# Load the Apache ModSecurity Connector Module
RUN echo "LoadModule security3_module /usr/lib/apache2/modules/mod_security3.so" >> /etc/apache2/apache2.conf

# Configure ModSecurity
RUN mkdir -p /etc/apache2/modsecurity.d/dd-rules && \
	cp modsecurity-v3.0.8/modsecurity.conf-recommended /etc/apache2/modsecurity.d/modsecurity.conf && \
	cp modsecurity-v3.0.8/unicode.mapping /etc/apache2/modsecurity.d/ && \
	sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/apache2/modsecurity.d/modsecurity.conf

ADD modsec_rules.conf /etc/apache2/modsecurity.d/

# Install OWASP ModSecurity Core Rule Set (CRS) on Ubuntu
RUN git clone --depth=1 https://github.com/SpiderLabs/owasp-modsecurity-crs.git /etc/apache2/modsecurity.d/owasp-crs
ADD crs-setup.conf /etc/apache2/modsecurity.d/owasp-crs/crs-setup.conf

# Activate ModSecurity
RUN mv /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf.old
ADD 000-default.conf /etc/apache2/sites-available/
ADD rules_apps.conf /etc/apache2/modsecurity.d/owasp-crs/rules/000-dd-apps.conf

RUN a2enmod proxy_http

#EXPOSE 80
#USER www-data
#HEALTHCHECK --interval=5s --timeout=3s CMD curl --fail http://localhost || exit 1
# Set and run a custom entrypoint
COPY docker-entrypoint.sh /
RUN chmod 777 /docker-entrypoint.sh && chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

# Testing ModSecurity
#curl http://<SERVER-IP/DOMAIN>/index.php?exec=/bin/bash
