145 Commits

Author SHA1 Message Date
bunkerity
15bdb076c8 hotfix - fix docs get_git_branch 2021-06-15 17:10:34 +02:00
bunkerity
d62c4f466d v1.2.7 release 2021-06-15 16:53:37 +02:00
bunkerity
ad52ef3260 autoconf - prevent race condition by checking health state 2021-06-15 09:52:33 +02:00
Bunkerity
3bd3b6fd7a Merge pull request #145 from thelittlefireman/patch-10
Upgrade ModSecurity-nginx to v1.0.2 - @thelittlefireman
2021-06-15 08:42:42 +02:00
thelittlefireman
e41acc20c2 Upgrade ModSecurity-nginx to v1.0.2 2021-06-15 00:01:23 +02:00
bunkerity
3c721dc2a0 add HEALTHCHECK to Dockerfile and append 10.0.0.0/8 to DNSBL whitelist 2021-06-14 20:54:36 +02:00
bunkerity
491d879fec jobs - cleaning the mess when using autoconf without swarm mode 2021-06-14 17:58:38 +02:00
bunkerity
52534510ec fix bug when AUTO_LETS_ENCRYPT=yes and certbot can't resolve challenges 2021-06-14 14:59:27 +02:00
bunkerity
2c7337576d jobs - fix syntax error 2021-06-14 13:39:27 +02:00
bunkerity
9e4961ccb5 docs - rename sitemap to bypass rtd rewrite 2021-06-14 10:21:30 +02:00
bunkerity
01857d8ac0 gen - display the reason when ignoring a variable 2021-06-14 09:58:04 +02:00
bunkerity
ab9f9e0a4c jobs - fix jobs when MULTISITE=yes 2021-06-14 09:02:16 +02:00
bunkerity
29dc64ca30 actions - add Docker cache to speedup auto build on the dev branch 2021-06-11 15:14:10 +02:00
bunkerity
b5cd4e0375 docker - build and push images from GitHub actions because of future DockerHub restrictions on autobuild 2021-06-11 13:39:39 +02:00
bunkerity
16101144c5 self-signed cert - fix bugs 2021-06-11 11:39:36 +02:00
bunkerity
95510e6e1d settings - add underscore to CUSTOM_HTTPS_CERT/KEY regex 2021-06-11 11:08:35 +02:00
bunkerity
dd5890e760 geoip - fix bug when using GeoIP 2021-06-11 11:01:13 +02:00
bunkerity
c3a437fa82 docs - rename the sitemap to avoid conflicts ? 2021-06-08 09:31:28 +02:00
bunkerity
518ddd3236 docs - custom robots.txt 2021-06-08 09:18:28 +02:00
bunkerity
177a82ee6e docs - automated sitemap.yml 2021-06-08 09:06:21 +02:00
bunkerity
39db7b368f v1.2.6 release 2021-06-07 10:30:33 +02:00
bunkerity
9442e59141 jobs - fix jobs in Swarm mode 2021-06-07 09:48:50 +02:00
bunkerity
fcc6b3b5e4 various bug fixes related to Swarm 2021-06-06 23:22:33 +02:00
florian
678ad70b01 docs, various fixes and certbot-cloudflare example 2021-06-06 14:52:30 +02:00
florian
e8f5db0b29 docs - add plugins system 2021-06-05 11:24:35 +02:00
florian
8295f6aeba plugins - clamav example 2021-06-05 00:29:24 +02:00
bunkerity
388fc1a0e8 plugins - started basic plugin system 2021-06-04 17:42:34 +02:00
bunkerity
62217a3210 add contributing guidelines and license 2021-06-04 10:08:11 +02:00
Bunkerity
53e433b1a4 readme - replace some badges 2021-06-03 23:37:10 +02:00
Bunkerity
f640157b1f Merge pull request #138 from bunkerity/feature-request-template
Update issue templates
2021-06-03 22:31:33 +02:00
Bunkerity
d646f3e5b7 Update issue templates 2021-06-03 22:30:31 +02:00
bunkerity
4b31d005eb crowdsec and generator fixes 2021-06-03 17:44:12 +02:00
bunkerity
d2135c19c0 docs - road to v1.2.6 2021-06-02 17:47:00 +02:00
bunkerity
8cda1baf77 fix web ui multiple variables and add default error pages 2021-06-02 15:33:42 +02:00
bunkerity
445032406b dnsbl - disable checks when IP is local 2021-06-02 13:46:57 +02:00
bunkerity
74fb015366 web UI - init work on using docker-socket-proxy 2021-06-02 12:12:30 +02:00
bunkerity
ee178de6ab web ui - mostly finished templating integration (needs some testing) 2021-06-01 15:22:03 +02:00
bunkerity
7323525b69 ui - show only multisite vars for settings 2021-06-01 10:54:59 +02:00
bunkerity
82e47f147d ui - Dockerfile fixes and missing get_config function 2021-05-31 21:06:05 +02:00
bunkerity
2db967ad1d templating - road to web ui 2021-05-31 17:49:37 +02:00
florian
1d96620ae6 templating - init integration into web ui 2021-05-31 09:48:26 +02:00
bunkerity
99c259bf18 templating - prepare integration into ui 2021-05-28 16:41:41 +02:00
bunkerity
c7b81cfc10 various bug fixes related to HTTPS 2021-05-28 14:57:45 +02:00
bunkerity
dfce0c06dd autoconf - fixing various bug when SWARM_MODE=yes 2021-05-28 12:16:56 +02:00
bunkerity
0f8e56a668 templating - fixing bugs with autoconf 2021-05-27 14:41:21 +02:00
bunkerity
f950abdc24 templating - started integration into autoconf 2021-05-27 12:34:00 +02:00
bunkerity
4a73ae8197 various bug fixes on templates and nginx update to 1.20.1 2021-05-27 09:53:14 +02:00
bunkerity
e2f02ee91e templating - prepare integration for autoconf 2021-05-26 20:50:03 +02:00
bunkerity
a991b262ef remove ClamAV because of GPL and started work on read-only filesystem 2021-05-26 17:18:49 +02:00
bunkerity
a8bc17e836 templating - started integration into docker image 2021-05-26 14:50:50 +02:00
bunkerity
ec19f93081 templating - added missing features in site templates 2021-05-25 17:07:06 +02:00
bunkerity
23aa053003 templating - auth basic support 2021-05-25 12:18:40 +02:00
bunkerity
289ad106cb templating - multisite support 2021-05-25 11:43:03 +02:00
bunkerity
bbc5bbc9e9 templating - fix some site templates 2021-05-24 20:52:17 +02:00
bunkerity
633a07686f templating - init work on site templates 2021-05-24 17:39:38 +02:00
bunkerity
996c45df42 templating - init work on global templates 2021-05-21 17:12:13 +02:00
bunkerity
801530baf3 templating - road to full jinja2 templates 2021-05-21 14:55:54 +02:00
bunkerity
c65dda3917 templating - init work on templating with jinja2 2021-05-21 11:54:37 +02:00
bunkerity
ea891969c1 templating - updated settings.json with global settings 2021-05-20 14:48:45 +02:00
bunkerity
698ae17c49 templating - init work on generic settings management 2021-05-20 12:27:35 +02:00
bunkerity
6645632846 antibot - basic pow with javascript 2021-05-19 17:36:29 +02:00
bunkerity
16e5ede130 antibot - custom templates 2021-05-19 16:37:28 +02:00
bunkerity
8260746fe1 logs/lua - add logger tool 2021-05-19 11:11:18 +02:00
florian
de560490d3 fix LUA array variables and add LOG_LEVEL to the troubleshooting section 2021-05-19 09:18:38 +02:00
florian
96db3a450d log - add LOG_LEVEL variable 2021-05-18 21:51:13 +02:00
florian
73543f4b0e hardening - add no-new-privileges 2021-05-18 21:35:58 +02:00
bunkerity
d9bb97be50 lua - move global vars from lua to site config (untested) 2021-05-18 17:29:00 +02:00
bunkerity
863283d090 started work on moving variables from .lua to nginx 2021-05-18 15:14:45 +02:00
bunkerity
600484b16e crowdsec - fix bugs and update example 2021-05-18 14:03:16 +02:00
bunkerity
7c6a13c549 examples - improve nextcloud example so it works with webdav clients 2021-05-17 10:26:35 +02:00
bunkerity
b3bb4ec40f remove unnecessary dependencies and update doc about certificate bundle 2021-05-15 21:55:57 +02:00
bunkerity
69f4657208 examples - fix typo BAD_BEHAVIOR_STATUS_CODES 2021-05-15 21:29:07 +02:00
bunkerity
d02985d213 check permissions for missing volumes and add comment about permissions on examples 2021-05-15 21:08:35 +02:00
bunkerity
b0ca85ff75 v1.2.5 - performance improvement 2021-05-14 16:42:08 +02:00
Bunkerity
2f115c444d Merge pull request #131 from bunkerity/issue-templates
Update issue templates
2021-05-14 16:37:37 +02:00
Bunkerity
7f15741ea2 Update issue templates 2021-05-14 16:33:01 +02:00
bunkerity
288b8eb851 docs improvement + road to v1.2.5 2021-05-14 15:41:15 +02:00
bunkerity
61c08fb97b docs - troubleshooting 2021-05-14 12:12:33 +02:00
bunkerity
01ef47a669 docs - security tuning improvement 2021-05-14 11:15:00 +02:00
florian
71515a9101 doc - volumes list 2021-05-13 20:34:41 +02:00
bunkerity
a33d0658c6 docs - road to a beautiful documentation 2021-05-13 17:46:31 +02:00
bunkerity
0b3ff6a9f4 bad behavior - move from fail2ban to pure lua 2021-05-13 16:21:51 +02:00
bunkerity
eb2d0d330d performance - rsyslog and fail2ban removing 2021-05-13 11:14:39 +02:00
bunkerity
5bcbb38638 doc - official document started 2021-05-12 17:35:32 +02:00
bunkerity
ca660b2501 init work on official doc 2021-05-12 12:28:01 +02:00
bunkerity
3a34436cd8 add AquaeAtrae example for ROOT_SITE_SUBFOLDER 2021-05-12 12:07:29 +02:00
bunkerity
b1d03cd11c performance - move bad user-agents and referrers checks from nginx to LUA with caching 2021-05-11 15:30:16 +02:00
bunkerity
42c3fb8740 add sandbox allow-downloads to the default value of CONTENT_SECURITY_POLICY 2021-05-11 08:57:23 +02:00
bunkerity
f1c043604a add missing backslash in the quickstart guide and update autoconf examples with the depends_on directive 2021-05-11 08:54:34 +02:00
bunkerity
fd61df205f performance - move external blacklists checks from nginx to LUA 2021-05-10 17:51:07 +02:00
bunkerity
009d6fb5ae choose connection and nofile numbers, increase error_log level to get modsecurity rules, add MODSECURITY_SEC_AUDIT_ENGINE var 2021-05-05 17:38:22 +02:00
bunkerity
ba4185a42e jobs - fix automatic reload 2021-05-03 14:18:10 +02:00
bunkerity
70976d0fbc fix user-agent not blocking and add documentation on bundle when USE_CUSTOM_HTTPS=yes 2021-05-03 13:59:55 +02:00
bunkerity
062a39c63a integrate AquaeAtrae work - add ROOT_SITE_SUBFOLDER 2021-05-03 10:31:37 +02:00
bunkerity
83841b290a jobs - edit adren work on external blacklists 2021-05-02 16:14:13 +02:00
Bunkerity
10dc58cb6d Merge pull request #126 from adren/patch-6
deduplicate list of user-agents
2021-05-02 15:14:10 +02:00
Bunkerity
668754686c Merge pull request #125 from adren/patch-5
more optimized way to generate map referrer file
2021-05-02 15:13:17 +02:00
Bunkerity
84b1933f63 Merge pull request #124 from adren/patch-4
improve the generation of blocking file (abusers)
2021-05-02 15:12:19 +02:00
Bunkerity
15f6d0a32a Merge pull request #123 from adren/patch-3
improve generation of block file (Tor exit nodes)
2021-05-02 15:11:27 +02:00
Bunkerity
e628361a89 Merge pull request #122 from adren/patch-1
huge improvement to generate blocking file
2021-05-02 15:10:52 +02:00
Cyril Chaboisseau
f8d71e067e improved way to generate user-agent file 2021-05-01 19:04:18 +02:00
Cyril Chaboisseau
02ae3b6bd3 change IFS before subshell
There needs to be a change in IFS before the 2 curl commands in order to keep line by line formatting
2021-05-01 15:48:33 +02:00
Cyril Chaboisseau
2fb0e7c473 deduplicate list of user-agents 2021-05-01 15:08:52 +02:00
Cyril Chaboisseau
9adcc2f1a7 more optimized way to generate map referrer file 2021-05-01 14:51:28 +02:00
Cyril Chaboisseau
7b98db4d14 improve the generation of blocking file (abusers) 2021-05-01 12:29:15 +02:00
Cyril Chaboisseau
ddb2b85916 improve generation of block file (Tor exit nodes) 2021-05-01 12:25:43 +02:00
Cyril Chaboisseau
da1a460a64 huge improvement to generate blocking file
process the file in 2 commands (grep + sed) instead of a loop running on each line
the time to generate the file takes 0.235 seconds instead of one hour, making it roughly 15,000 times quicker
the output file is exactly the same as with the former method
2021-05-01 11:42:07 +02:00
bunkerity
07be626842 hotfix - fix API in autoconf swarm mode 2021-04-28 17:40:54 +02:00
bunkerity
3bb164395e hotfix - move API_WHITELIST_IP edit to lua.sh 2021-04-28 17:00:50 +02:00
bunkerity
bc2568a172 v1.2.4 - nginx 1.20.0 support 2021-04-27 17:43:38 +02:00
Bunkerity
5ec74880d8 update README for v1.2.4 2021-04-27 17:40:33 +02:00
bunkerity
f84fd7c9a2 fix permissions issues for autoconf and fix volume for ghost example 2021-04-27 16:49:45 +02:00
bunkerity
6521d7a27a fix client cache so it works in combination with reverse proxy and examples update 2021-04-27 15:31:56 +02:00
bunkerity
813607fbc3 improve crowdsec example and disable modsec logging when not necessary 2021-04-27 11:21:30 +02:00
bunkerity
843644f806 log - replace some WARN tags from LUA logs with NOTICE to avoid confusion 2021-04-27 09:57:07 +02:00
bunkerity
19fa0eb25f log - print modsec_audit.log to make debugging easier 2021-04-27 09:46:40 +02:00
bunkerity
b4df287228 log - send logs to remote syslog server 2021-04-27 09:30:10 +02:00
florian
5ce41edc03 api - whitelist IP/network for API 2021-04-26 22:22:34 +02:00
florian
a3cfb50b4d example - fix certbot wildcard 2021-04-26 21:34:18 +02:00
bunkerity
25494acace example - wildcard certificate with certbot 2021-04-26 17:44:48 +02:00
bunkerity
a98dae1fb6 fix CVE-2021-20205 and examples update 2021-04-26 17:00:23 +02:00
bunkerity
1a7abab570 nginx 1.20.0 support 2021-04-26 14:59:12 +02:00
florian
42b7a57f01 fix autoconf bug when removing config with multiple server name and increase default LIMIT_CONN_MAX for average website with HTTP2 2021-04-26 11:39:12 +02:00
bunkerity
02f9fbe5fc autoconf - fix certbot bug when multiple server_name for one service 2021-04-20 11:46:53 +02:00
bunkerity
69fe066777 autoconf - fix bug when multiple server_name for one service 2021-04-20 10:00:25 +02:00
bunkerity
74417abc9c fixing bugs - run as GID 101 instead of 0, different permissions checks in swarm mode and disable including server confs in swarm mode 2021-04-16 16:56:45 +02:00
bunkerity
ba7524a419 fixed LUA bug 2021-04-13 17:27:52 +02:00
bunkerity
b55aafb997 finding the LUA bug 2021-04-13 17:01:27 +02:00
Bunkerity
deeb7a76a2 Merge pull request #117 from thelittlefireman/patch-9
Fix lua mistake
2021-04-13 16:49:45 +02:00
thelittlefireman
ee8aaa4e7e fix lua crash 2 2021-04-11 15:45:46 +02:00
thelittlefireman
605d59a45c Fix lua mistake
#116
2021-04-11 15:33:31 +02:00
bunkerity
b85c991b6e bug fixes - /usr/local/lib/lua rights and syntax error in site-config 2021-04-09 17:40:19 +02:00
bunkerity
0d3658adf0 REVERSE_PROXY_HEADERS - use proxy_set_header instead of more_set_headers 2021-04-09 17:27:22 +02:00
bunkerity
0b22209c96 documentation - userns remap feature 2021-04-09 16:22:31 +02:00
bunkerity
e44a1f3e14 added the uri to limit_req_zone key to limit bruteforce attack on a specific resource instead of the whole service 2021-04-09 15:54:26 +02:00
bunkerity
aa614f82f9 print error when permissions are wrong on common volumes 2021-04-09 14:54:15 +02:00
bunkerity
c03d410b0a refactored whitelisting of user-agents 2021-04-09 14:23:52 +02:00
bunkerity
e190167bfc CIDR support with whitelist/blacklist IP 2021-04-09 14:10:17 +02:00
bunkerity
31e72dce1c fix /usr/local/lib/lua rights and multiple server_name support with autoconf 2021-04-09 11:37:13 +02:00
bunkerity
b8105fc558 feature - whitelist URI 2021-04-09 10:31:00 +02:00
bunkerity
e73c10fd80 crowdsec - fix permissions on /usr/local/lib/lua and on /var/log files 2021-04-09 10:01:23 +02:00
bunkerity
a122a259c0 minor fix on AutoConf logs and auto disable etag with reverse proxy 2021-04-09 09:51:17 +02:00
bunkerity
7c4894d3b8 autoconf - fix remove event, generate config from nginx vars, more logs 2021-03-26 15:18:35 +01:00
bunkerity
533c2a1034 fix sed script when writing site env 2021-03-22 09:38:36 +01:00
bunkerity
5611d544d6 remove reference to USE_PHP 2021-03-19 09:38:44 +01:00
244 changed files with 8028 additions and 4786 deletions

17
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,17 @@
---
name: Bug report
about: Something is not working as expected
title: "[BUG]"
labels: bug
assignees: ''
---
**Description**
Concise description of what you're trying to do, the expected behavior and the current bug.
**How to reproduce**
Give steps on how to reproduce the bug (e.g. : commands, configs, tests, environment, version, ...).
**Logs**
The logs generated by bunkerized-nginx. **DON'T FORGET TO REMOVE PRIVATE DATA LIKE IP ADDRESSES !**

View File

@@ -0,0 +1,14 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[FEATURE]"
labels: enhancement
assignees: ''
---
**What's needed and why ?**
Describe the feature you would like to see in the project and why it should be implemented.
**Implementations ideas (optional)**
How it should be used and integrated into the project ? List some posts, research papers or codes that we can use as implementation.

View File

@@ -24,5 +24,3 @@ jobs:
exit-code: '1'
ignore-unfixed: true
severity: 'UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL'

View File

@@ -0,0 +1,50 @@
name: Build and push bunkerized-nginx-autoconf
on:
push:
branches: [dev, master]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v2
- name: Set variables
run: |
VER=$(cat VERSION | tr -d '\n')
echo "VERSION=$VER" >> $GITHUB_ENV
- name: Setup QEMU
uses: docker/setup-qemu-action@v1
- name: Setup Buildx
uses: docker/setup-buildx-action@v1
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Build and push (dev)
uses: docker/build-push-action@v2
if: github.ref == 'refs/heads/dev'
with:
context: .
file: autoconf/Dockerfile
platforms: linux/amd64,linux/386,linux/arm/v7,linux/arm64/v8
push: true
tags: bunkerity/bunkerized-nginx-autoconf:dev
- name: Build and push (master)
uses: docker/build-push-action@v2
if: github.ref == 'refs/heads/master'
with:
context: .
file: autoconf/Dockerfile
platforms: linux/amd64,linux/386,linux/arm/v7,linux/arm64/v8
push: true
tags: bunkerity/bunkerized-nginx-autoconf:latest,bunkerity/bunkerized-nginx-autoconf:${{ env.VERSION }}

View File

@@ -0,0 +1,50 @@
name: Build and push bunkerized-nginx-ui
on:
push:
branches: [dev, master]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v2
- name: Set variables
run: |
VER=$(cat VERSION | tr -d '\n')
echo "VERSION=$VER" >> $GITHUB_ENV
- name: Setup QEMU
uses: docker/setup-qemu-action@v1
- name: Setup Buildx
uses: docker/setup-buildx-action@v1
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Build and push (dev)
uses: docker/build-push-action@v2
if: github.ref == 'refs/heads/dev'
with:
context: .
file: ui/Dockerfile
platforms: linux/amd64,linux/386,linux/arm/v7,linux/arm64/v8
push: true
tags: bunkerity/bunkerized-nginx-ui:dev
- name: Build and push (master)
uses: docker/build-push-action@v2
if: github.ref == 'refs/heads/master'
with:
context: .
file: ui/Dockerfile
platforms: linux/amd64,linux/386,linux/arm/v7,linux/arm64/v8
push: true
tags: bunkerity/bunkerized-nginx-ui:latest,bunkerity/bunkerized-nginx-ui:${{ env.VERSION }}

View File

@@ -0,0 +1,65 @@
name: Build and push bunkerized-nginx
on:
push:
branches: [dev, master]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v2
- name: Set variables
run: |
VER=$(cat VERSION | tr -d '\n')
echo "VERSION=$VER" >> $GITHUB_ENV
- name: Setup QEMU
uses: docker/setup-qemu-action@v1
- name: Setup Buildx
uses: docker/setup-buildx-action@v1
- name: Setup Docker cache
uses: actions/cache@v2
if: github.ref == 'refs/heads/dev'
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Build and push (dev)
uses: docker/build-push-action@v2
if: github.ref == 'refs/heads/dev'
with:
context: .
platforms: linux/amd64,linux/386,linux/arm/v7,linux/arm64/v8
push: true
tags: bunkerity/bunkerized-nginx:dev
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache-new
- name: Move Docker cache
if: github.ref == 'refs/heads/dev'
run: |
rm -rf /tmp/.buildx-cache
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
- name: Build and push (master)
uses: docker/build-push-action@v2
if: github.ref == 'refs/heads/master'
with:
context: .
platforms: linux/amd64,linux/386,linux/arm/v7,linux/arm64/v8
push: true
tags: bunkerity/bunkerized-nginx:latest,bunkerity/bunkerized-nginx:${{ env.VERSION }}

1
.gitignore vendored
View File

@@ -1 +1,2 @@
.idea/
docs/_build/

41
CHANGELOG.md Normal file
View File

@@ -0,0 +1,41 @@
# Changelog
## v1.2.7 - 2021/06/14
- Add custom robots.txt and sitemap to RTD
- Fix missing GeoIP DB bug when using BLACKLIST/WHITELIST_COUNTRY
- Add underscore "_" to allowed chars for CUSTOM_HTTPS_CERT/KEY
- Fix bug when using automatic self-signed certificate
- Build and push images from GitHub actions instead of Docker Hub autobuild
- Display the reason when generator is ignoring a variable
- Various bug fixes related to certbot and jobs
- Split jobs into pre and post jobs
- Add HEALTHCHECK to image
- Fix race condition when using autoconf without Swarm by checking healthy state
- Bump modsecurity-nginx to v1.0.2
- Community chat with bridged platforms
## v1.2.6 - 2021/06/06
- Move from "ghetto-style" shell scripts to generic jinja2 templating
- Init work on a basic plugins system
- Move ClamAV to external plugin
- Reduce image size by removing unnecessary dependencies
- Fix CrowdSec example
- Change some global variables to multisite
- Add LOG_LEVEL environment variable
- Read-only container support
- Improved antibot javascript with a basic proof of work
- Update nginx to 1.20.1
- Support of docker-socket-proxy with web UI
- Add certbot-cloudflare example
- Disable DNSBL checks when IP is local
## v1.2.5 - 2021/05/14
- Performance improvement : move some nginx security checks to LUA and external blacklist parsing enhancement
- Init work on official documentation on readthedocs
- Fix default value for CONTENT_SECURITY_POLICY to allow file downloads
- Add ROOT_SITE_SUBFOLDER environment variable
## TODO - retrospective changelog

24
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,24 @@
# Contributing to bunkerized-nginx
First off all, thanks for being here and showing your support to the project !
We accept many types of contributions whether they are technical or not. Every community feedback, work or help is, and will always be, appreciated.
## Talk about the project
The first thing you can do is to talk about the project. You can share it on social media, make a blog post about it or simply tell your friends/colleagues that's an awesome project.
## Join the community chat
You can join [the community chat](https://coso.me/bunkerity-chat) to talk about the project and ask for help. Please note that you can choose the platform you want, thanks to [matterbridge](https://github.com/42wim/matterbridge) all messages coming from a platform are relayed to the others.
## Reporting bugs / ask for features
The preferred way to report bugs and asking for features is using [issues](https://github.com/bunkerity/bunkerized-nginx/issues). Before opening a new one, please check if a related issue is already opened using the "filters" bar. When creating a new issue please select and fill the "Bug report" or "Feature request" template.
## Code contribution
The preferred way to contribute code is using [pull requests](https://github.com/bunkerity/bunkerized-nginx/pulls). Before creating a pull request, please check if your code is related to an opened issue. If that's not the case, you should first create an issue so we can discuss about it. This procedure is here to avoid wasting your time in case the PR will be rejected. For minor changes (e.g. : typo, quick fix, ...), opening an issue might be facultative. **Don't forget to edit the documentations when needed !**

View File

@@ -1,4 +1,4 @@
FROM nginx:stable-alpine
FROM nginx:1.20.1-alpine
COPY nginx-keys/ /tmp/nginx-keys
COPY compile.sh /tmp/compile.sh
@@ -6,20 +6,35 @@ RUN chmod +x /tmp/compile.sh && \
/tmp/compile.sh && \
rm -rf /tmp/*
COPY dependencies.sh /tmp/dependencies.sh
RUN chmod +x /tmp/dependencies.sh && \
/tmp/dependencies.sh && \
rm -rf /tmp/dependencies.sh
COPY gen/ /opt/gen
COPY entrypoint/ /opt/entrypoint
COPY confs/ /opt/confs
COPY scripts/ /opt/scripts
COPY fail2ban/ /opt/fail2ban
COPY logs/ /opt/logs
COPY lua/ /opt/lua
COPY lua/ /usr/local/lib/lua
COPY antibot/ /antibot
COPY defaults/ /defaults
COPY settings.json /opt
COPY misc/cron /etc/crontabs/nginx
COPY prepare.sh /tmp/prepare.sh
RUN chmod +x /tmp/prepare.sh && /tmp/prepare.sh && rm -f /tmp/prepare.sh
RUN chmod +x /tmp/prepare.sh && \
/tmp/prepare.sh && \
rm -f /tmp/prepare.sh
VOLUME /www /http-confs /server-confs /modsec-confs /modsec-crs-confs /cache /pre-server-confs /acme-challenge
# Fix CVE-2021-22901, CVE-2021-22898 and CVE-2021-22897
RUN apk add "curl>=7.77.0-r0"
VOLUME /www /http-confs /server-confs /modsec-confs /modsec-crs-confs /cache /pre-server-confs /acme-challenge /plugins
EXPOSE 8080/tcp 8443/tcp
USER nginx
USER nginx:nginx
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 CMD [ -f /tmp/nginx.pid ] || exit 1
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,25 +0,0 @@
FROM amd64/nginx:stable-alpine
COPY nginx-keys/ /tmp/nginx-keys
COPY compile.sh /tmp/compile.sh
RUN chmod +x /tmp/compile.sh && \
/tmp/compile.sh && \
rm -rf /tmp/*
COPY entrypoint/ /opt/entrypoint
COPY confs/ /opt/confs
COPY scripts/ /opt/scripts
COPY fail2ban/ /opt/fail2ban
COPY logs/ /opt/logs
COPY lua/ /opt/lua
COPY prepare.sh /tmp/prepare.sh
RUN chmod +x /tmp/prepare.sh && /tmp/prepare.sh && rm -f /tmp/prepare.sh
VOLUME /www /http-confs /server-confs /modsec-confs /modsec-crs-confs /cache /pre-server-confs /acme-challenge
EXPOSE 8080/tcp 8443/tcp
USER nginx
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,32 +0,0 @@
FROM alpine AS builder
ENV QEMU_URL https://github.com/balena-io/qemu/releases/download/v4.0.0%2Bbalena2/qemu-4.0.0.balena2-arm.tar.gz
RUN apk add curl && curl -L ${QEMU_URL} | tar zxvf - -C . --strip-components 1
FROM arm32v7/nginx:stable-alpine
COPY --from=builder qemu-arm-static /usr/bin
COPY nginx-keys/ /tmp/nginx-keys
COPY compile.sh /tmp/compile.sh
RUN chmod +x /tmp/compile.sh && \
/tmp/compile.sh && \
rm -rf /tmp/*
COPY entrypoint/ /opt/entrypoint
COPY confs/ /opt/confs
COPY scripts/ /opt/scripts
COPY fail2ban/ /opt/fail2ban
COPY logs/ /opt/logs
COPY lua/ /opt/lua
COPY prepare.sh /tmp/prepare.sh
RUN chmod +x /tmp/prepare.sh && /tmp/prepare.sh && rm -f /tmp/prepare.sh
VOLUME /www /http-confs /server-confs /modsec-confs /modsec-crs-confs /cache /pre-server-confs /acme-challenge
EXPOSE 8080/tcp 8443/tcp
USER nginx
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,32 +0,0 @@
FROM alpine AS builder
ENV QEMU_URL https://github.com/balena-io/qemu/releases/download/v4.0.0%2Bbalena2/qemu-4.0.0.balena2-aarch64.tar.gz
RUN apk add curl && curl -L ${QEMU_URL} | tar zxvf - -C . --strip-components 1
FROM arm64v8/nginx:stable-alpine
COPY --from=builder qemu-aarch64-static /usr/bin
COPY nginx-keys/ /tmp/nginx-keys
COPY compile.sh /tmp/compile.sh
RUN chmod +x /tmp/compile.sh && \
/tmp/compile.sh && \
rm -rf /tmp/*
COPY entrypoint/ /opt/entrypoint
COPY confs/ /opt/confs
COPY scripts/ /opt/scripts
COPY fail2ban/ /opt/fail2ban
COPY logs/ /opt/logs
COPY lua/ /opt/lua
COPY prepare.sh /tmp/prepare.sh
RUN chmod +x /tmp/prepare.sh && /tmp/prepare.sh && rm -f /tmp/prepare.sh
VOLUME /www /http-confs /server-confs /modsec-confs /modsec-crs-confs /cache /pre-server-confs /acme-challenge
EXPOSE 8080/tcp 8443/tcp
USER nginx
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,25 +0,0 @@
FROM i386/nginx:stable-alpine
COPY nginx-keys/ /tmp/nginx-keys
COPY compile.sh /tmp/compile.sh
RUN chmod +x /tmp/compile.sh && \
/tmp/compile.sh && \
rm -rf /tmp/*
COPY entrypoint/ /opt/entrypoint
COPY confs/ /opt/confs
COPY scripts/ /opt/scripts
COPY fail2ban/ /opt/fail2ban
COPY logs/ /opt/logs
COPY lua/ /opt/lua
COPY prepare.sh /tmp/prepare.sh
RUN chmod +x /tmp/prepare.sh && /tmp/prepare.sh && rm -f /tmp/prepare.sh
VOLUME /www /http-confs /server-confs /modsec-confs /modsec-crs-confs /cache /pre-server-confs /acme-challenge
EXPOSE 8080/tcp 8443/tcp
USER nginx
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

660
LICENSE.md Normal file
View File

@@ -0,0 +1,660 @@
### GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing
under this license.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public
License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your
version supports such interaction) an opportunity to receive the
Corresponding Source of your version by providing access to the
Corresponding Source from a network server at no charge, through some
standard or customary means of facilitating copying of software. This
Corresponding Source shall include the Corresponding Source for any
work covered by version 3 of the GNU General Public License that is
incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever
published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for
the specific requirements.
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU AGPL, see <https://www.gnu.org/licenses/>.

1164
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -1 +1 @@
1.2.3
1.2.7

5
antibot/captcha.data Normal file
View File

@@ -0,0 +1,5 @@
<form method="POST" action="%s">
<img src="data:image/jpeg;base64,%s" /><br>
Captcha : <input type="text" name="captcha" /><br />
<input type="submit" value="send" />
</form>

24
antibot/captcha.html Normal file
View File

@@ -0,0 +1,24 @@
<html>
<head>
<title>Website protection</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>As a security measure, we ask you to complete this captcha to access our website :</h1>
%CAPTCHA%
<div>&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;</div>
</div>
</body>
</html>

29
antibot/javascript.data Normal file
View File

@@ -0,0 +1,29 @@
<script>
async function digestMessage(message) {
const msgUint8 = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
(async () => {
const nonce = '%s';
var i = 0;
while (true) {
var digestHex = await digestMessage(nonce + i.toString());
if (digestHex.startsWith("0000")) {
break;
}
i++;
}
xhr = new XMLHttpRequest();
xhr.open('POST', '%s');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
window.location.replace('%s');
}
};
xhr.send(encodeURI('challenge=' + i.toString()));
})();
</script>

43
antibot/javascript.html Normal file
View File

@@ -0,0 +1,43 @@
<html>
<head>
<title>Website protection</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.loader {
border: 16px solid #1d70b7;
border-top: 16px solid #2dab66;
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
display: block;
margin-left: auto;
margin-right: auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<div class="loader"></div>
<noscript>
<h1 style="color: red;">In order to access this website, you need to enable JavaScript.</h1>
</noscript>
<h1>Please wait while we are doing some security checks...</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
%JAVASCRIPT%
</body>
</html>

View File

@@ -0,0 +1,11 @@
<form method="POST" action="%s" id="form">
<input type="hidden" name="token" id="token">
</form>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('%s', {action: 'recaptcha'}).then(function(token) {
document.getElementById("token").value = token;
document.getElementById("form").submit();
});;
});
</script>

View File

@@ -0,0 +1 @@
<script src="https://www.google.com/recaptcha/api.js?render=%s"></script>

44
antibot/recaptcha.html Normal file
View File

@@ -0,0 +1,44 @@
<html>
<head>
<title>Website protection</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.loader {
border: 16px solid #1d70b7;
border-top: 16px solid #2dab66;
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
display: block;
margin-left: auto;
margin-right: auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
%RECAPTCHA_HEAD%
</head>
<body>
<div class="centered" style="color: white;">
<div class="loader"></div>
<noscript>
<h1 style="color: red;">In order to access this website, you need to enable JavaScript.</h1>
</noscript>
<h1>Please wait while we are doing some security checks...</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
%RECAPTCHA_BODY%
</body>
</html>

View File

@@ -1,6 +1,8 @@
from Config import Config
import utils
import os
import os, time
class AutoConf :
@@ -8,12 +10,47 @@ class AutoConf :
self.__swarm = swarm
self.__servers = {}
self.__instances = {}
self.__sites = {}
self.__env = {}
self.__config = Config(self.__swarm, api)
def get_server(self, id) :
if id in self.__servers :
return self.__servers[id]
return False
def reload(self) :
return self.__config.reload(self.__instances)
def __gen_env(self) :
self.__env.clear()
# TODO : check actual state (e.g. : running, stopped ?)
for id, instance in self.__instances.items() :
env = []
if self.__swarm :
env = instance.attrs["Spec"]["TaskTemplate"]["ContainerSpec"]["Env"]
else :
env = instance.attrs["Config"]["Env"]
for entry in env :
self.__env[entry.split("=")[0]] = entry.replace(entry.split("=")[0] + "=", "", 1)
blacklist = ["NGINX_VERSION", "NJS_VERSION", "PATH", "PKG_RELEASE"]
for entry in blacklist :
if entry in self.__env :
del self.__env[entry]
if not "SERVER_NAME" in self.__env or self.__env["SERVER_NAME"] == "" :
self.__env["SERVER_NAME"] = []
else :
self.__env["SERVER_NAME"] = self.__env["SERVER_NAME"].split(" ")
for server in self.__servers :
(id, name, labels) = self.__get_infos(self.__servers[server])
first_server = labels["bunkerized-nginx.SERVER_NAME"].split(" ")[0]
for label in labels :
if label.startswith("bunkerized-nginx.") :
self.__env[first_server + "_" + label.replace("bunkerized-nginx.", "", 1)] = labels[label]
for server_name in labels["bunkerized-nginx.SERVER_NAME"].split(" ") :
if not server_name in self.__env["SERVER_NAME"] :
self.__env["SERVER_NAME"].append(server_name)
self.__env["SERVER_NAME"] = " ".join(self.__env["SERVER_NAME"])
def pre_process(self, objs) :
for instance in objs :
(id, name, labels) = self.__get_infos(instance)
@@ -56,65 +93,103 @@ class AutoConf :
return (id, name, labels)
def __process_instance(self, instance, event, id, name, labels) :
if event == "create" :
self.__instances[id] = instance
if self.__swarm and len(self.__instances) == 1 :
if self.__config.initconf(self.__instances) :
utils.log("[*] initial config succeeded")
else :
utils.log("[!] initial config failed")
self.__gen_env()
utils.log("[*] bunkerized-nginx instance created : " + name + " / " + id)
if self.__swarm and len(self.__instances) == 1 :
if self.__config.generate(self.__env) :
utils.log("[*] Initial config succeeded")
if not self.__config.swarm_wait(self.__instances) :
utils.log("[!] Removing bunkerized-nginx instances from list (API not available)")
del self.__instances[id]
else :
utils.log("[!] Initial config failed")
elif not self.__swarm and len(self.__instances) == 1 :
utils.log("[*] Wait until bunkerized-nginx is healthy (timeout = 120s) ...")
i = 0
healthy = False
while i < 120 :
self.__instances[id].reload()
if self.__instances[id].attrs["State"]["Health"]["Status"] == "healthy" :
healthy = True
break
time.sleep(1)
i = i + 1
if not healthy :
utils.log("[!] Removing bunkerized-nginx instances from list (unhealthy)")
del self.__instances[id]
elif event == "start" :
self.__instances[id].reload()
self.__gen_env()
utils.log("[*] bunkerized-nginx instance started : " + name + " / " + id)
elif event == "die" :
self.__instances[id].reload()
self.__gen_env()
utils.log("[*] bunkerized-nginx instance stopped : " + name + " / " + id)
elif event == "destroy" or event == "remove" :
del self.__instances[id]
if self.__swarm and len(self.__instances) == 0 :
with open("/etc/crontabs/nginx", "w") as f :
f.write("")
if os.path.exists("/etc/nginx/autoconf") :
os.remove("/etc/nginx/autoconf")
self.__gen_env()
utils.log("[*] bunkerized-nginx instance removed : " + name + " / " + id)
def __process_server(self, instance, event, id, name, labels) :
vars = { k.replace("bunkerized-nginx.", "", 1) : v for k, v in labels.items() if k.startswith("bunkerized-nginx.")}
if event == "create" :
if self.__config.generate(self.__instances, vars) :
utils.log("[*] Generating config for " + vars["SERVER_NAME"] + " ...")
self.__servers[id] = instance
self.__gen_env()
if self.__config.generate(self.__env) :
utils.log("[*] Generated config for " + vars["SERVER_NAME"])
self.__servers[id] = instance
if self.__swarm :
if self.__config.activate(self.__instances, vars) :
utils.log("[*] Activating config for " + vars["SERVER_NAME"] + " ...")
if self.__config.reload(self.__instances) :
utils.log("[*] Activated config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't activate config for " + vars["SERVER_NAME"])
utils.log("[!] Can't activate config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't generate config for " + vars["SERVER_NAME"])
del self.__servers[id]
self.__gen_env()
self.__config.generate(self.__env)
elif event == "start" :
if id in self.__servers :
self.__servers[id].reload()
if self.__config.activate(self.__instances, vars) :
utils.log("[*] Activating config for " + vars["SERVER_NAME"] + " ...")
self.__gen_env()
if self.__config.reload(self.__instances) :
utils.log("[*] Activated config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't activate config for " + vars["SERVER_NAME"])
elif event == "die" :
if id in self.__servers :
self.__servers[id].reload()
if self.__config.deactivate(self.__instances, vars) :
utils.log("[*] Deactivating config for " + vars["SERVER_NAME"])
self.__gen_env()
if self.__config.reload() :
utils.log("[*] Deactivated config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't deactivate config for " + vars["SERVER_NAME"])
elif event == "destroy" or event == "remove" :
if id in self.__servers :
if self.__swarm :
if self.__config.deactivate(self.__instances, vars) :
utils.log("[*] Deactivated config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't deactivate config for " + vars["SERVER_NAME"])
utils.log("[*] Removing config for " + vars["SERVER_NAME"])
del self.__servers[id]
if self.__config.remove(vars) :
self.__gen_env()
if self.__config.generate(self.__env) :
utils.log("[*] Removed config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't remove config for " + vars["SERVER_NAME"])
utils.log("[*] Deactivating config for " + vars["SERVER_NAME"])
if self.__config.reload(self.__instances) :
utils.log("[*] Deactivated config for " + vars["SERVER_NAME"])
else :
utils.log("[!] Can't deactivate config for " + vars["SERVER_NAME"])

View File

@@ -9,135 +9,82 @@ class Config :
self.__swarm = swarm
self.__api = api
def __jobs(self, type) :
utils.log("[*] Starting jobs (type = " + type + ") ...")
proc = subprocess.run(["/bin/su", "-c", "/opt/entrypoint/" + type + "-jobs.sh", "nginx"], capture_output=True)
stdout = proc.stdout.decode("ascii")
stderr = proc.stderr.decode("ascii")
if len(stdout) > 1 :
utils.log("[*] Jobs stdout :")
utils.log(stdout)
if stderr != "" :
utils.log("[!] Jobs stderr :")
utils.log(stderr)
if proc.returncode != 0 :
utils.log("[!] Jobs error : return code != 0")
return False
return True
def initconf(self, instances) :
def swarm_wait(self, instances) :
try :
for instance_id, instance in instances.items() :
env = instance.attrs["Spec"]["TaskTemplate"]["ContainerSpec"]["Env"]
break
vars = {}
for var_value in env :
var = var_value.split("=")[0]
value = var_value.replace(var + "=", "", 1)
vars[var] = value
if self.globalconf(instances) :
i = 0
started = False
while i < 10 :
if self.__ping(instances) :
started = True
break
i = i + 1
utils.log("[!] Waiting " + str(i) + " seconds before retrying to contact nginx instances")
time.sleep(i)
if started :
proc = subprocess.run(["/bin/su", "-s", "/opt/entrypoint/jobs.sh", "nginx"], env=vars, capture_output=True)
return proc.returncode == 0
else :
utils.log("[!] bunkerized-nginx instances are not started")
else :
utils.log("[!] Can't generate global conf")
except Exception as e :
traceback.print_exc()
utils.log("[!] Error while initializing config : " + str(e))
return False
def globalconf(self, instances) :
try :
for instance_id, instance in instances.items() :
env = instance.attrs["Spec"]["TaskTemplate"]["ContainerSpec"]["Env"]
break
vars = {}
for var_value in env :
var = var_value.split("=")[0]
value = var_value.replace(var + "=", "", 1)
vars[var] = value
proc = subprocess.run(["/bin/su", "-s", "/opt/entrypoint/global-config.sh", "nginx"], env=vars, capture_output=True)
if proc.returncode == 0 :
with open("/etc/nginx/autoconf", "w") as f :
f.write("ok")
with open("/etc/nginx/autoconf", "w") as f :
f.write("ok")
utils.log("[*] Waiting for bunkerized-nginx tasks ...")
i = 1
started = False
while i <= 10 :
time.sleep(i)
if self.__ping(instances) :
started = True
break
i = i + 1
utils.log("[!] Waiting " + str(i) + " seconds before retrying to contact bunkerized-nginx tasks")
if started :
utils.log("[*] bunkerized-nginx tasks started")
return True
else :
utils.log("[!] bunkerized-nginx tasks are not started")
except Exception as e :
traceback.print_exc()
utils.log("[!] Error while generating global config : " + str(e))
utils.log("[!] Error while waiting for Swarm tasks : " + str(e))
return False
def generate(self, instances, vars) :
def generate(self, env) :
try :
# Get env vars from bunkerized-nginx instances
vars_instances = {}
for instance_id, instance in instances.items() :
# Write environment variables to a file
with open("/tmp/variables.env", "w") as f :
for k, v in env.items() :
f.write(k + "=" + v + "\n")
# Call the generator
proc = subprocess.run(["/bin/su", "-c", "/opt/gen/main.py --settings /opt/settings.json --templates /opt/confs --output /etc/nginx --variables /tmp/variables.env", "nginx"], capture_output=True)
# Print stdout/stderr
stdout = proc.stdout.decode("ascii")
stderr = proc.stderr.decode("ascii")
if len(stdout) > 1 :
utils.log("[*] Generator output :")
utils.log(stdout)
if stderr != "" :
utils.log("[*] Generator error :")
utils.log(error)
# We're done
if proc.returncode == 0 :
if self.__swarm :
env = instance.attrs["Spec"]["TaskTemplate"]["ContainerSpec"]["Env"]
else :
env = instance.attrs["Config"]["Env"]
for var_value in env :
var = var_value.split("=")[0]
value = var_value.replace(var + "=", "", 1)
vars_instances[var] = value
vars_defaults = vars.copy()
vars_defaults.update(vars_instances)
vars_defaults.update(vars)
# Call site-config.sh to generate the config
proc = subprocess.run(["/bin/su", "-s", "/bin/sh", "-c", "/opt/entrypoint/site-config.sh" + " " + vars["SERVER_NAME"], "nginx"], env=vars_defaults, capture_output=True)
if proc.returncode == 0 and vars_defaults["MULTISITE"] == "yes" and self.__swarm :
proc = subprocess.run(["/bin/su", "-s", "/opt/entrypoint/multisite-config.sh", "nginx"], env=vars_defaults, capture_output=True)
return proc.returncode == 0
return proc.returncode == 0
except Exception as e :
traceback.print_exc()
utils.log("[!] Error while generating site config : " + str(e))
return False
def activate(self, instances, vars) :
try :
# Check if file exists
if not os.path.isfile("/etc/nginx/" + vars["SERVER_NAME"] + "/server.conf") :
utils.log("[!] /etc/nginx/" + vars["SERVER_NAME"] + "/server.conf doesn't exist")
return False
# Include the server conf
utils.replace_in_file("/etc/nginx/nginx.conf", "}", "include /etc/nginx/" + vars["SERVER_NAME"] + "/server.conf;\n}")
return self.reload(instances)
except Exception as e :
traceback.print_exc()
utils.log("[!] Error while activating config : " + str(e))
return False
def deactivate(self, instances, vars) :
try :
# Check if file exists
if not os.path.isfile("/etc/nginx/" + vars["SERVER_NAME"] + "/server.conf") :
utils.log("[!] /etc/nginx/" + vars["SERVER_NAME"] + "/server.conf doesn't exist")
return False
# Remove the include
utils.replace_in_file("/etc/nginx/nginx.conf", "include /etc/nginx/" + vars["SERVER_NAME"] + "/server.conf;\n", "")
return self.reload(instances)
return self.__jobs("pre")
return True
utils.log("[!] Error while generating site config for " + env["SERVER_NAME"] + " : return code = " + str(proc.returncode))
except Exception as e :
traceback.print_exc()
utils.log("[!] Error while deactivating config : " + str(e))
return False
def remove(self, instances, vars) :
try :
# Check if file exists
if not os.path.isfile("/etc/nginx/" + vars["SERVER_NAME"] + "/server.conf") :
utils.log("[!] /etc/nginx/" + vars["SERVER_NAME"] + "/server.conf doesn't exist")
return False
# Remove the folder
shutil.rmtree("/etc/nginx/" + vars["SERVER_NAME"])
return True
except Exception as e :
utils.log("[!] Error while deactivating config : " + str(e))
utils.log("[!] Exception while generating site config : " + str(e))
return False
def reload(self, instances) :
return self.__api_call(instances, "/reload")
if self.__api_call(instances, "/reload") :
if self.__swarm :
return self.__jobs("post")
return True
return False
def __ping(self, instances) :
return self.__api_call(instances, "/ping")
@@ -149,7 +96,7 @@ class Config :
instance.reload()
# Reload via API
if self.__swarm :
# Send POST request on http://serviceName.NodeID.TaskID:8000/reload
# Send POST request on http://serviceName.NodeID.TaskID:8000/action
name = instance.name
for task in instance.tasks() :
if task["Status"]["State"] != "running" :
@@ -162,7 +109,7 @@ class Config :
req = requests.post("http://" + fqdn + ":8080" + self.__api + path)
except :
pass
if req and req.status_code == 200 :
if req and req.status_code == 200 and req.text == "ok" :
utils.log("[*] Sent API order " + path + " to instance " + fqdn + " (service.node.task)")
else :
utils.log("[!] Can't send API order " + path + " to instance " + fqdn + " (service.node.task)")

View File

@@ -1,38 +1,22 @@
FROM nginx:stable-alpine AS builder
FROM alpine
COPY --from=builder /etc/nginx/ /opt/confs/nginx
COPY autoconf/dependencies.sh /tmp
RUN chmod +x /tmp/dependencies.sh && \
/tmp/dependencies.sh && \
rm -f /tmp/dependencies.sh
RUN apk add py3-pip apache2-utils bash certbot curl logrotate openssl && \
pip3 install docker requests && \
mkdir /opt/entrypoint && \
mkdir -p /opt/confs/site && \
mkdir -p /opt/confs/global && \
mkdir /opt/scripts && \
addgroup -g 101 nginx && \
adduser -h /var/cache/nginx -g nginx -s /sbin/nologin -G nginx -D -H -u 101 nginx && \
mkdir /var/log/letsencrypt && \
chown root:nginx /var/log/letsencrypt && \
chmod 770 /var/log/letsencrypt && \
mkdir /var/lib/letsencrypt && \
chown root:nginx /var/lib/letsencrypt && \
chmod 770 /var/lib/letsencrypt && \
mkdir /cache && \
chown root:nginx /cache && \
chmod 770 /cache && \
touch /var/log/jobs.log && \
chown root:nginx /var/log/jobs.log && \
chmod 770 /var/log/jobs.log && \
chown -R root:nginx /opt/confs/nginx && \
chmod -R 770 /opt/confs/nginx
COPY autoconf/misc/logrotate.conf /etc/logrotate.conf
COPY scripts/* /opt/scripts/
COPY confs/site/ /opt/confs/site
COPY gen/ /opt/gen
COPY entrypoint/ /opt/entrypoint
COPY confs/global/ /opt/confs/global
COPY entrypoint/* /opt/entrypoint/
COPY confs/site/ /opt/confs/site
COPY scripts/ /opt/scripts
COPY settings.json /opt
COPY misc/cron /etc/crontabs/nginx
COPY autoconf/* /opt/entrypoint/
RUN chmod +x /opt/entrypoint/*.py /opt/entrypoint/*.sh /opt/scripts/*.sh
COPY autoconf/prepare.sh /tmp
RUN chmod +x /tmp/prepare.sh && \
/tmp/prepare.sh && \
rm -f /tmp/prepare.sh
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,37 +0,0 @@
FROM nginx:stable-alpine AS builder
FROM amd64/alpine
COPY --from=builder /etc/nginx/ /opt/confs/nginx
RUN apk add py3-pip apache2-utils bash certbot curl logrotate openssl && \
pip3 install docker requests && \
mkdir /opt/entrypoint && \
mkdir -p /opt/confs/site && \
mkdir -p /opt/confs/global && \
addgroup -g 101 nginx && \
adduser -h /var/cache/nginx -g nginx -s /sbin/nologin -G nginx -D -H -u 101 nginx && \
mkdir /var/log/letsencrypt && \
chown root:nginx /var/log/letsencrypt && \
chmod 770 /var/log/letsencrypt && \
mkdir /var/lib/letsencrypt && \
chown root:nginx /var/lib/letsencrypt && \
chmod 770 /var/lib/letsencrypt && \
mkdir /cache && \
chown root:nginx /cache && \
chmod 770 /cache && \
touch /var/log/jobs.log && \
chown root:nginx /var/log/jobs.log && \
chmod 770 /var/log/jobs.log && \
chown -R root:nginx /opt/confs/nginx && \
chmod -R 770 /opt/confs/nginx
COPY autoconf/misc/logrotate.conf /etc/logrotate.conf
COPY scripts/* /opt/scripts/
COPY confs/global/ /opt/confs/global
COPY confs/site/ /opt/confs/site
COPY entrypoint/* /opt/entrypoint/
COPY autoconf/* /opt/entrypoint/
RUN chmod +x /opt/entrypoint/*.py /opt/entrypoint/*.sh /opt/scripts/*.sh
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,43 +0,0 @@
FROM alpine AS builder
ENV QEMU_URL https://github.com/balena-io/qemu/releases/download/v4.0.0%2Bbalena2/qemu-4.0.0.balena2-arm.tar.gz
RUN apk add curl && curl -L ${QEMU_URL} | tar zxvf - -C . --strip-components 1
FROM nginx:stable-alpine AS builder2
FROM arm32v7/alpine
COPY --from=builder qemu-arm-static /usr/bin
COPY --from=builder2 /etc/nginx/ /opt/confs/nginx
RUN apk add py3-pip apache2-utils bash certbot curl logrotate openssl && \
pip3 install docker requests && \
mkdir /opt/entrypoint && \
mkdir -p /opt/confs/site && \
mkdir -p /opt/confs/global && \
addgroup -g 101 nginx && \
adduser -h /var/cache/nginx -g nginx -s /sbin/nologin -G nginx -D -H -u 101 nginx && \
mkdir /var/log/letsencrypt && \
chown root:nginx /var/log/letsencrypt && \
chmod 770 /var/log/letsencrypt && \
mkdir /var/lib/letsencrypt && \
chown root:nginx /var/lib/letsencrypt && \
chmod 770 /var/lib/letsencrypt && \
mkdir /cache && \
chown root:nginx /cache && \
chmod 770 /cache && \
touch /var/log/jobs.log && \
chown root:nginx /var/log/jobs.log && \
chmod 770 /var/log/jobs.log && \
chown -R root:nginx /opt/confs/nginx && \
chmod -R 770 /opt/confs/nginx
COPY autoconf/misc/logrotate.conf /etc/logrotate.conf
COPY scripts/* /opt/scripts/
COPY confs/global/ /opt/confs/global
COPY confs/site/ /opt/confs/site
COPY entrypoint/* /opt/entrypoint/
COPY autoconf/* /opt/entrypoint/
RUN chmod +x /opt/entrypoint/*.py /opt/entrypoint/*.sh /opt/scripts/*.sh
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,43 +0,0 @@
FROM alpine AS builder
ENV QEMU_URL https://github.com/balena-io/qemu/releases/download/v4.0.0%2Bbalena2/qemu-4.0.0.balena2-aarch64.tar.gz
RUN apk add curl && curl -L ${QEMU_URL} | tar zxvf - -C . --strip-components 1
FROM nginx:stable-alpine AS builder2
FROM arm64v8/alpine
COPY --from=builder qemu-aarch64-static /usr/bin
COPY --from=builder2 /etc/nginx/ /opt/confs/nginx
RUN apk add py3-pip apache2-utils bash certbot curl logrotate openssl && \
pip3 install docker requests && \
mkdir /opt/entrypoint && \
mkdir -p /opt/confs/site && \
mkdir -p /opt/confs/global && \
addgroup -g 101 nginx && \
adduser -h /var/cache/nginx -g nginx -s /sbin/nologin -G nginx -D -H -u 101 nginx && \
mkdir /var/log/letsencrypt && \
chown root:nginx /var/log/letsencrypt && \
chmod 770 /var/log/letsencrypt && \
mkdir /var/lib/letsencrypt && \
chown root:nginx /var/lib/letsencrypt && \
chmod 770 /var/lib/letsencrypt && \
mkdir /cache && \
chown root:nginx /cache && \
chmod 770 /cache && \
touch /var/log/jobs.log && \
chown root:nginx /var/log/jobs.log && \
chmod 770 /var/log/jobs.log && \
chown -R root:nginx /opt/confs/nginx && \
chmod -R 770 /opt/confs/nginx
COPY autoconf/misc/logrotate.conf /etc/logrotate.conf
COPY scripts/* /opt/scripts/
COPY confs/global/ /opt/confs/global
COPY confs/site/ /opt/confs/site
COPY entrypoint/* /opt/entrypoint/
COPY autoconf/* /opt/entrypoint/
RUN chmod +x /opt/entrypoint/*.py /opt/entrypoint/*.sh /opt/scripts/*.sh
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -1,37 +0,0 @@
FROM nginx:stable-alpine AS builder
FROM i386/alpine
COPY --from=builder /etc/nginx/ /opt/confs/nginx
RUN apk add py3-pip apache2-utils bash certbot curl logrotate openssl && \
pip3 install docker requests && \
mkdir /opt/entrypoint && \
mkdir -p /opt/confs/site && \
mkdir -p /opt/confs/global && \
addgroup -g 101 nginx && \
adduser -h /var/cache/nginx -g nginx -s /sbin/nologin -G nginx -D -H -u 101 nginx && \
mkdir /var/log/letsencrypt && \
chown root:nginx /var/log/letsencrypt && \
chmod 770 /var/log/letsencrypt && \
mkdir /var/lib/letsencrypt && \
chown root:nginx /var/lib/letsencrypt && \
chmod 770 /var/lib/letsencrypt && \
mkdir /cache && \
chown root:nginx /cache && \
chmod 770 /cache && \
touch /var/log/jobs.log && \
chown root:nginx /var/log/jobs.log && \
chmod 770 /var/log/jobs.log && \
chown -R root:nginx /opt/confs/nginx && \
chmod -R 770 /opt/confs/nginx
COPY autoconf/misc/logrotate.conf /etc/logrotate.conf
COPY scripts/* /opt/scripts/
COPY confs/global/ /opt/confs/global
COPY confs/site/ /opt/confs/site
COPY entrypoint/* /opt/entrypoint/
COPY autoconf/* /opt/entrypoint/
RUN chmod +x /opt/entrypoint/*.py /opt/entrypoint/*.sh /opt/scripts/*.sh
ENTRYPOINT ["/opt/entrypoint/entrypoint.sh"]

View File

@@ -39,11 +39,11 @@ except docker.errors.APIError as e :
sys.exit(3)
# Process them before events
with lock :
autoconf.pre_process(before)
autoconf.pre_process(before)
# Process events received from Docker
try :
utils.log("[*] Listening for Docker events ...")
for event in client.events(decode=True) :
# Process only container/service events
@@ -53,15 +53,18 @@ try :
# Get Container/Service object
try :
if swarm :
server = client.services.get(service_id=event["Actor"]["ID"])
id = service_id=event["Actor"]["ID"]
server = client.services.get(service_id=id)
else :
server = client.containers.get(event["id"])
id = event["id"]
server = client.containers.get(id)
except docker.errors.NotFound as e :
continue
server = autoconf.get_server(id)
if not server :
continue
# Process the event
with lock :
autoconf.process(server, event["Action"])
autoconf.process(server, event["Action"])
except docker.errors.APIError as e :
utils.log("[!] Docker API error " + str(e))

5
autoconf/dependencies.sh Normal file
View File

@@ -0,0 +1,5 @@
#!/bin/sh
# install dependencies
apk add py3-pip bash certbot curl openssl
pip3 install docker requests jinja2

View File

@@ -2,8 +2,13 @@
echo "[*] Starting autoconf ..."
# check permissions
su -s "/opt/entrypoint/permissions.sh" nginx
if [ "$?" -ne 0 ] ; then
exit 1
fi
if [ "$SWARM_MODE" = "yes" ] ; then
cp -r /opt/confs/nginx/* /etc/nginx
chown -R root:nginx /etc/nginx
chmod -R 770 /etc/nginx
fi
@@ -13,28 +18,19 @@ function trap_exit() {
echo "[*] Catched stop operation"
echo "[*] Stopping crond ..."
pkill -TERM crond
echo "[*] Stopping python3 ..."
echo "[*] Stopping autoconf ..."
pkill -TERM python3
pkill -TERM tail
}
trap "trap_exit" TERM INT QUIT
# remove old crontabs
echo "" > /etc/crontabs/root
# setup logrotate
touch /var/log/jobs.log
echo "0 0 * * * /usr/sbin/logrotate -f /etc/logrotate.conf > /dev/null 2>&1" >> /etc/crontabs/root
# start cron
crond
# run autoconf app
/opt/entrypoint/app.py &
# display logs
tail -F /var/log/jobs.log &
pid="$!"
# wait while app is up
wait "$pid"
# stop

View File

@@ -1,23 +0,0 @@
/var/log/*.log /var/log/letsencrypt/*.log {
# compress old files using gzip
compress
# rotate everyday
daily
# remove old logs after X days
maxage 7
rotate 7
# no errors if a file is missing
missingok
# disable mailing
nomail
# mininum size of a logfile before rotating
minsize 10M
# make a copy and truncate the files
copytruncate
}

44
autoconf/prepare.sh Normal file
View File

@@ -0,0 +1,44 @@
#!/bin/sh
# create nginx user
addgroup -g 101 nginx
adduser -h /var/cache/nginx -g nginx -s /bin/sh -G nginx -D -H -u 101 nginx
# prepare /opt
chown -R root:nginx /opt
find /opt -type f -exec chmod 0740 {} \;
find /opt -type d -exec chmod 0750 {} \;
chmod ugo+x /opt/entrypoint/* /opt/scripts/*
chmod ugo+x /opt/gen/main.py
chmod 770 /opt
chmod 440 /opt/settings.json
# prepare /var/log
ln -s /proc/1/fd/1 /var/log/jobs.log
mkdir /var/log/letsencrypt
chown nginx:nginx /var/log/letsencrypt
chmod 770 /var/log/letsencrypt
# prepare /etc/letsencrypt
mkdir /etc/letsencrypt
chown root:nginx /etc/letsencrypt
chmod 770 /etc/letsencrypt
# prepare /var/lib/letsencrypt
mkdir /var/lib/letsencrypt
chown root:nginx /var/lib/letsencrypt
chmod 770 /var/lib/letsencrypt
# prepare /cache
mkdir /cache
chown root:nginx /cache
chmod 770 /cache
# prepare /acme-challenge
mkdir /acme-challenge
chown root:nginx /acme-challenge
chmod 770 /acme-challenge
# prepare /etc/crontabs/nginx
chown root:nginx /etc/crontabs/nginx
chmod 440 /etc/crontabs/nginx

View File

@@ -57,7 +57,7 @@ cp crs-setup.conf.example /opt/owasp/crs.conf
# get nginx modules
cd /tmp
# ModSecurity connector for nginx
git_secure_clone https://github.com/SpiderLabs/ModSecurity-nginx.git 22e53aba4e3ae8c7d59a3672d6727e49246afe96
git_secure_clone https://github.com/SpiderLabs/ModSecurity-nginx.git 2497e6ac654d0b117b9534aa735b757c6b11c84f
# headers more
git_secure_clone https://github.com/openresty/headers-more-nginx-module.git d6d7ebab3c0c5b32ab421ba186783d3e5d2c6a17
# geoip
@@ -130,12 +130,13 @@ git_secure_clone https://github.com/crowdsecurity/lua-cs-bouncer.git 3c235c813fc
cd lua-cs-bouncer
mkdir /usr/local/lib/lua/crowdsec
cp lib/*.lua /usr/local/lib/lua/crowdsec
cp template.conf /usr/local/lib/lua/crowdsec/crowdsec.conf
sed -i 's/^API_URL=.*/API_URL=%CROWDSEC_HOST%/' /usr/local/lib/lua/crowdsec/crowdsec.conf
sed -i 's/^API_KEY=.*/API_KEY=%CROWDSEC_KEY%/' /usr/local/lib/lua/crowdsec/crowdsec.conf
sed -i 's/require "lrucache"/require "resty.lrucache"/' /usr/local/lib/lua/crowdsec/CrowdSec.lua
sed -i 's/require "config"/require "crowdsec.config"/' /usr/local/lib/lua/crowdsec/CrowdSec.lua
cd /tmp
git_secure_clone https://github.com/hamishforbes/lua-resty-iputils.git 3151d6485e830421266eee5c0f386c32c835dba4
cd lua-resty-iputils
make LUA_LIB_DIR=/usr/local/lib/lua install
cd /tmp
git_secure_clone https://github.com/openresty/lua-nginx-module.git 2d23bc4f0a29ed79aaaa754c11bffb1080aa44ba
export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.1
@@ -153,7 +154,7 @@ fi
tar -xvzf nginx-${NGINX_VERSION}.tar.gz
cd nginx-$NGINX_VERSION
CONFARGS=$(nginx -V 2>&1 | sed -n -e 's/^.*arguments: //p')
CONFARGS=${CONFARGS/-Os -fomit-frame-pointer/-Os}
CONFARGS=${CONFARGS/-Os -fomit-frame-pointer -g/-Os}
./configure $CONFARGS --add-dynamic-module=/tmp/ModSecurity-nginx --add-dynamic-module=/tmp/headers-more-nginx-module --add-dynamic-module=/tmp/ngx_http_geoip2_module --add-dynamic-module=/tmp/nginx_cookie_flag_module --add-dynamic-module=/tmp/lua-nginx-module --add-dynamic-module=/tmp/ngx_brotli
make -j $NTASK modules
cp ./objs/*.so /usr/lib/nginx/modules

View File

@@ -1,22 +1,23 @@
location ~ ^%API_URI%/ping {
return 444;
}
location ~ ^%API_URI% {
location ~ %API_URI% {
rewrite_by_lua_block {
local api = require "api"
local api_uri = "%API_URI%"
local api = require "api"
local api_whitelist_ip = { %API_WHITELIST_IP% }
local api_uri = "%API_URI%"
local logger = require "logger"
if api.is_api_call(api_uri) then
if api.is_api_call(api_uri, api_whitelist_ip) then
ngx.header.content_type = 'text/plain'
if api.do_api_call(api_uri) then
ngx.log(ngx.WARN, "[API] API call " .. ngx.var.request_uri .. " successfull from " .. ngx.var.remote_addr)
logger.log(ngx.NOTICE, "API", "API call " .. ngx.var.request_uri .. " successfull from " .. ngx.var.remote_addr)
ngx.say("ok")
else
ngx.log(ngx.WARN, "[API] API call " .. ngx.var.request_uri .. " failed from " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "API", "API call " .. ngx.var.request_uri .. " failed from " .. ngx.var.remote_addr)
ngx.say("ko")
end

View File

@@ -1,16 +1,19 @@
# todo : if api_uri == "random"
rewrite_by_lua_block {
local api = require "api"
local api_uri = "%API_URI%"
local api = require "api"
local api_whitelist_ip = {% raw %}{{% endraw %}{% if API_WHITELIST_IP != ""%}{% set elements = API_WHITELIST_IP.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
local api_uri = "{{ API_URI }}"
local logger = require "logger"
if api.is_api_call(api_uri) then
if api.is_api_call(api_uri, api_whitelist_ip) then
ngx.header.content_type = 'text/plain'
if api.do_api_call(api_uri) then
ngx.log(ngx.WARN, "[API] API call " .. ngx.var.request_uri .. " successfull from " .. ngx.var.remote_addr)
ngx.say("ok")
logger.log(ngx.NOTICE, "API", "API call " .. ngx.var.request_uri .. " successfull from " .. ngx.var.remote_addr)
ngx.print("ok")
else
ngx.log(ngx.WARN, "[API] API call " .. ngx.var.request_uri .. " failed from " .. ngx.var.remote_addr)
ngx.say("ko")
logger.log(ngx.WARN, "API", "API call " .. ngx.var.request_uri .. " failed from " .. ngx.var.remote_addr)
ngx.print("ko")
end
ngx.exit(ngx.HTTP_OK)

View File

@@ -1,4 +0,0 @@
open_file_cache %CACHE%;
open_file_cache_errors %CACHE_ERRORS%;
open_file_cache_min_uses %CACHE_USES%;
open_file_cache_valid %CACHE_VALID%;

View File

@@ -1,9 +1,5 @@
init_by_lua_block {
local cs = require "crowdsec.CrowdSec"
local ok, err = cs.init("/usr/local/lib/lua/crowdsec/crowdsec.conf")
if ok == nil then
ngx.log(ngx.ERR, "[Crowdsec] " .. err)
error()
end
ngx.log(ngx.ERR, "[Crowdsec] Initialisation done")
}
API_URL={{ CROWDSEC_HOST }}
API_KEY={{ CROWDSEC_KEY }}
LOG_FILE=/tmp/lua_mod.log
CACHE_EXPIRATION=1
CACHE_SIZE=1000

25
confs/global/fastcgi.conf Normal file
View File

@@ -0,0 +1,25 @@
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REQUEST_SCHEME $scheme;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;

View File

@@ -5,6 +5,15 @@ geoip2 /etc/nginx/geoip.mmdb {
}
map $geoip2_data_country_code $allowed_country {
default %DEFAULT%;
%COUNTRY%
default {% if WHITELIST_COUNTRY != "" %}no{% else %}yes{% endif %};
{% if WHITELIST_COUNTRY != "" %}
{% for country in WHITELIST_COUNTRY.split(" ") %}
{{ country }} yes;
{% endfor %}
{% endif %}
{% if BLACKLIST_COUNTRY != "" %}
{% for country in BLACKLIST_COUNTRY.split(" ") %}
{{ country }} no;
{% endfor %}
{% endif %}
}

View File

@@ -0,0 +1,72 @@
init_by_lua_block {
local dataloader = require "dataloader"
local logger = require "logger"
local cjson = require "cjson"
local use_proxies = {% if has_value("BLOCK_PROXIES", "yes") %}true{% else %}false{% endif %}
local use_abusers = {% if has_value("BLOCK_ABUSERS", "yes") %}true{% else %}false{% endif %}
local use_tor_exit_nodes = {% if has_value("BLOCK_TOR_EXIT_NODE", "yes") %}true{% else %}false{% endif %}
local use_user_agents = {% if has_value("BLOCK_USER_AGENT", "yes") %}true{% else %}false{% endif %}
local use_referrers = {% if has_value("BLOCK_REFERRER", "yes") %}true{% else %}false{% endif %}
local use_crowdsec = {% if has_value("USE_CROWDSEC", "yes") %}true{% else %}false{% endif %}
if use_proxies then
dataloader.load_ip("/etc/nginx/proxies.list", ngx.shared.proxies_data)
end
if use_abusers then
dataloader.load_ip("/etc/nginx/abusers.list", ngx.shared.abusers_data)
end
if use_tor_exit_nodes then
dataloader.load_ip("/etc/nginx/tor-exit-nodes.list", ngx.shared.tor_exit_nodes_data)
end
if use_user_agents then
dataloader.load_raw("/etc/nginx/user-agents.list", ngx.shared.user_agents_data)
end
if use_referrers then
dataloader.load_raw("/etc/nginx/referrers.list", ngx.shared.referrers_data)
end
if use_crowdsec then
local cs = require "crowdsec.CrowdSec"
local ok, err = cs.init("/etc/nginx/crowdsec.conf")
if ok == nil then
logger.log(ngx.ERR, "CROWDSEC", err)
error()
end
logger.log(ngx.ERR, "CROWDSEC", "*NOT AN ERROR* initialisation done")
end
-- Load plugins
ngx.shared.plugins_data:safe_set("plugins", nil, 0)
local p = io.popen("find /plugins -maxdepth 1 -type d ! -path /plugins")
for dir in p:lines() do
-- read JSON
local file = io.open(dir .. "/plugin.json")
if file then
-- store settings
local data = cjson.decode(file:read("*a"))
for k, v in pairs(data.settings) do
ngx.shared.plugins_data:safe_set(data.id .. "_" .. k, v, 0)
end
file:close()
-- store plugin
local plugins, flags = ngx.shared.plugins_data:get("plugins")
if plugins == nil then
ngx.shared.plugins_data:safe_set("plugins", data.id, 0)
else
ngx.shared.plugins_data:safe_set("plugins", plugins .. " " .. data.id, 0)
end
logger.log(ngx.ERR, "PLUGINS", "*NOT AN ERROR* plugin " .. data.name .. "/" .. data.version .. " has been loaded")
else
logger.log(ngx.ERR, "PLUGINS", "Can't load " .. dir .. "/plugin.json")
end
end
p:close()
}

View File

@@ -1 +0,0 @@
map $http_referer $bad_referrer { hostnames; default no; }

View File

@@ -1 +0,0 @@
map $http_user_agent $bad_user_agent { default no; }

96
confs/global/mime.types Normal file
View File

@@ -0,0 +1,96 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;
text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;
image/png png;
image/svg+xml svg svgz;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/webp webp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;
font/woff woff;
font/woff2 woff2;
application/java-archive jar war ear;
application/json json;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.apple.mpegurl m3u8;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/vnd.ms-excel xls;
application/vnd.ms-fontobject eot;
application/vnd.ms-powerpoint ppt;
application/vnd.oasis.opendocument.graphics odg;
application/vnd.oasis.opendocument.presentation odp;
application/vnd.oasis.opendocument.spreadsheet ods;
application/vnd.oasis.opendocument.text odt;
application/vnd.openxmlformats-officedocument.presentationml.presentation
pptx;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xlsx;
application/vnd.openxmlformats-officedocument.wordprocessingml.document
docx;
application/vnd.wap.wmlc wmlc;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/xspf+xml xspf;
application/zip zip;
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream iso img;
application/octet-stream msi msp msm;
audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;
video/3gpp 3gpp 3gp;
video/mp2t ts;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
}

View File

@@ -1,11 +1,13 @@
listen 0.0.0.0:%HTTPS_PORT% default_server ssl %HTTP2%;
listen 0.0.0.0:{{ HTTPS_PORT }} default_server ssl {% if USE_HTTP2 == "yes" %}http2{% endif %};
ssl_certificate /etc/nginx/default-cert.pem;
ssl_certificate_key /etc/nginx/default-key.pem;
ssl_protocols %HTTPS_PROTOCOLS%;
ssl_protocols {{ HTTPS_PROTOCOLS }};
ssl_prefer_server_ciphers off;
ssl_session_tickets off;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m;
%SSL_DHPARAM%
%SSL_CIPHERS%
%LETS_ENCRYPT_WEBROOT%
{% if "TLSv1.2" in HTTPS_PROTOCOLS %}
ssl_dhparam /etc/nginx/dhparam;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
{% endif %}
include /etc/nginx/multisite-default-server-lets-encrypt-webroot.conf;

View File

@@ -1,6 +1,11 @@
server {
%LISTEN_HTTP%
{% if LISTEN_HTTP == "yes" %}listen 0.0.0.0:{{ HTTP_PORT }} default_server{% endif %};
server_name _;
%USE_HTTPS%
%MULTISITE_DISABLE_DEFAULT_SERVER%
{% if has_value("AUTO_LETS_ENCRYPT", "yes") %}include /etc/nginx/multisite-default-server-https.conf;{% endif %}
{% if USE_API == "yes" %}
location ^~ {{ API_URI }} {
include /etc/nginx/api.conf;
}
{% endif %}
{% if DISABLE_DEFAULT_SERVER == "yes" %}include /etc/nginx/multisite-disable-default-server.conf;{% endif %}
}

View File

@@ -10,8 +10,8 @@ load_module /usr/lib/nginx/modules/ngx_stream_geoip2_module.so;
load_module /usr/lib/nginx/modules/ngx_http_brotli_filter_module.so;
load_module /usr/lib/nginx/modules/ngx_http_brotli_static_module.so;
# run as daemon
daemon on;
# run in foreground
daemon off;
# PID file
pid /tmp/nginx.pid;
@@ -25,9 +25,12 @@ pcre_jit on;
# config files for dynamic modules
include /etc/nginx/modules/*.conf;
# max open files for each worker
worker_rlimit_nofile {{ WORKER_RLIMIT_NOFILE }};
events {
# max connections per worker
worker_connections 1024;
worker_connections {{ WORKER_CONNECTIONS }};
# epoll seems to be the best on Linux
use epoll;
@@ -48,9 +51,9 @@ http {
default_type application/octet-stream;
# write logs to local syslog
log_format logf '%LOG_FORMAT%';
access_log syslog:server=unix:/tmp/log,nohostname,facility=local0,severity=notice logf;
error_log syslog:server=unix:/tmp/log,nohostname,facility=local0 warn;
log_format logf '{{ LOG_FORMAT }}';
access_log /var/log/access.log logf;
error_log /var/log/error.log {{ LOG_LEVEL }};
# temp paths
proxy_temp_path /tmp/proxy_temp;
@@ -63,55 +66,84 @@ http {
reset_timedout_connection on;
# timeouts
client_body_timeout 12;
client_header_timeout 12;
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 15;
send_timeout 10;
# resolvers to use
resolver %DNS_RESOLVERS% ipv6=off;
resolver {{ DNS_RESOLVERS }} ipv6=off;
# remove ports when sending redirects
port_in_redirect off;
# lua path and dicts
lua_package_path "/usr/local/lib/lua/?.lua;;";
%WHITELIST_IP_CACHE%
%WHITELIST_REVERSE_CACHE%
%BLACKLIST_IP_CACHE%
%BLACKLIST_REVERSE_CACHE%
%DNSBL_CACHE%
lua_package_path "/usr/local/lib/lua/?.lua;/plugins/?.lua;;";
{% if has_value("USE_WHITELIST_IP", "yes") %}lua_shared_dict whitelist_ip_cache 10m;{% endif %}
{% if has_value("USE_WHITELIST_REVERSE", "yes") %}lua_shared_dict whitelist_reverse_cache 10m;{% endif %}
{% if has_value("USE_BLACKLIST_IP", "yes") %}lua_shared_dict blacklist_ip_cache 10m;{% endif %}
{% if has_value("USE_BLACKLIST_REVERSE", "yes") %}lua_shared_dict blacklist_reverse_cache 10m;{% endif %}
{% if has_value("USE_DNSBL", "yes") %}lua_shared_dict dnsbl_cache 10m;{% endif %}
{% if has_value("BLOCK_PROXIES", "yes") %}lua_shared_dict proxies_data 250m;{% endif %}
{% if has_value("BLOCK_ABUSERS", "yes") %}lua_shared_dict abusers_data 50m;{% endif %}
{% if has_value("BLOCK_TOR_EXIT_NODE", "yes") %}lua_shared_dict tor_exit_nodes_data 1m;{% endif %}
{% if has_value("BLOCK_USER_AGENT", "yes") %}lua_shared_dict user_agents_data 1m;{% endif %}
{% if has_value("BLOCK_USER_AGENT", "yes") %}lua_shared_dict user_agents_cache 10m;{% endif %}
{% if has_value("BLOCK_REFERRER", "yes") %}lua_shared_dict referrers_data 1m;{% endif %}
{% if has_value("BLOCK_REFERRER", "yes") %}lua_shared_dict referrers_cache 10m;{% endif %}
{% if has_value("USE_BAD_BEHAVIOR", "yes") %}lua_shared_dict behavior_ban 10m;{% endif %}
{% if has_value("USE_BAD_BEHAVIOR", "yes") %}lua_shared_dict behavior_count 10m;{% endif %}
lua_shared_dict plugins_data 10m;
# crowdsec init
%USE_CROWDSEC%
# shared memory zone for limit_req
%LIMIT_REQ_ZONE%
{% if has_value("USE_LIMIT_REQ", "yes") %}limit_req_zone $binary_remote_addr$uri zone=limit:{{ LIMIT_REQ_CACHE }} rate={{ LIMIT_REQ_RATE }};{% endif %}
# shared memory zone for limit_conn
%LIMIT_CONN_ZONE%
{% if has_value("USE_LIMIT_CONN", "yes") %}limit_conn_zone $binary_remote_addr zone=ddos:{{ LIMIT_CONN_CACHE }};{% endif %}
# whitelist or blacklist country
%USE_COUNTRY%
# list of blocked user agents
%BLOCK_USER_AGENT%
# list of blocked referrers
%BLOCK_REFERRER%
{% if BLACKLIST_COUNTRY != "" or WHITELIST_COUNTRY != "" %}include /etc/nginx/geoip.conf;{% endif %}
# zone for proxy_cache
%PROXY_CACHE_PATH%
{% if has_value("USE_PROXY_CACHE", "yes") %}proxy_cache_path /tmp/proxy_cache keys_zone=proxycache:{{ PROXY_CACHE_PATH_ZONE_SIZE }} {{ PROXY_CACHE_PATH_PARAMS }};{% endif %}
# custom http confs
include /http-confs/*.conf;
# LUA init block
include /etc/nginx/init-lua.conf;
# default server when MULTISITE=yes
%MULTISITE_DEFAULT_SERVER%
{% if MULTISITE == "yes" %}include /etc/nginx/multisite-default-server.conf;{% endif %}
# server config(s)
%INCLUDE_SERVER%
{% if MULTISITE == "yes" and SERVER_NAME != "" %}
{% set map_servers = {} %}
{% for server_name in SERVER_NAME.split(" ") %}
{% if server_name + "_SERVER_NAME" in all %}
{% set x = map_servers.update({server_name : all[server_name + "_SERVER_NAME"].split(" ")}) %}
{% endif %}
{% endfor %}
{% for server_name in SERVER_NAME.split(" ") %}
{% if not server_name in map_servers %}
{% set found = {"res": false} %}
{% for first_server, servers in map_servers.items() %}
{% if server_name in servers %}
{% set x = found.update({"res" : true}) %}
{% endif %}
{% endfor %}
{% if not found["res"] %}
{% set x = map_servers.update({server_name : [server_name]}) %}
{% endif %}
{% endif %}
{% endfor %}
{% for first_server in map_servers %}
include /etc/nginx/{{ first_server }}/server.conf;
{% endfor %}
{% elif MULTISITE == "no" %}
include /etc/nginx/server.conf;
{% endif %}
# API
%USE_API%
{% if USE_API == "yes" %}include /etc/nginx/api.conf;{% endif %}
}

View File

View File

View File

@@ -1,4 +1,4 @@
location = %ANTIBOT_URI% {
location = {{ ANTIBOT_URI }} {
default_type 'text/html';
@@ -6,13 +6,14 @@ location = %ANTIBOT_URI% {
content_by_lua_block {
local cookie = require "cookie"
local captcha = require "captcha"
local logger = require "logger"
if not cookie.is_set("uri") then
ngx.log(ngx.WARN, "[ANTIBOT] captcha fail (1) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "captcha fail (1) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
local img, res = captcha.get_challenge()
cookie.set({captchares = res})
local code = captcha.get_code(img, "%ANTIBOT_URI%")
local code = captcha.get_code(img, "{{ ANTIBOT_URI }}")
ngx.say(code)
}
}
@@ -21,21 +22,22 @@ location = %ANTIBOT_URI% {
access_by_lua_block {
local cookie = require "cookie"
local captcha = require "captcha"
local logger = require "logger"
if not cookie.is_set("captchares") then
ngx.log(ngx.WARN, "[ANTIBOT] captcha fail (2) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "captcha fail (2) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
ngx.req.read_body()
local args, err = ngx.req.get_post_args(1)
if err == "truncated" or not args or not args["captcha"] then
ngx.log(ngx.WARN, "[ANTIBOT] captcha fail (3) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "captcha fail (3) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
local captcha_user = args["captcha"]
local check = captcha.check(captcha_user, cookie.get("captchares"))
if not check then
ngx.log(ngx.WARN, "[ANTIBOT] captcha fail (4) for " .. ngx.var.remote_addr)
return ngx.redirect("%ANTIBOT_URI%")
logger.log(ngx.WARN, "ANTIBOT", "captcha fail (4) for " .. ngx.var.remote_addr)
return ngx.redirect("{{ ANTIBOT_URI }}")
end
cookie.set({captcha = "ok"})
return ngx.redirect(cookie.get("uri"))

View File

@@ -1,4 +1,4 @@
location = %ANTIBOT_URI% {
location = {{ ANTIBOT_URI }} {
default_type 'text/html';
@@ -6,12 +6,13 @@ location = %ANTIBOT_URI% {
content_by_lua_block {
local cookie = require "cookie"
local javascript = require "javascript"
local logger = require "logger"
if not cookie.is_set("challenge") then
ngx.log(ngx.WARN, "[ANTIBOT] javascript fail (1) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "javascript fail (1) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
local challenge = cookie.get("challenge")
local code = javascript.get_code(challenge, "%ANTIBOT_URI%", cookie.get("uri"))
local code = javascript.get_code(challenge, "{{ ANTIBOT_URI }}", cookie.get("uri"))
ngx.say(code)
}
}
@@ -20,20 +21,21 @@ location = %ANTIBOT_URI% {
content_by_lua_block {
local cookie = require "cookie"
local javascript = require "javascript"
local logger = require "logger"
if not cookie.is_set("challenge") then
ngx.log(ngx.WARN, "[ANTIBOT] javascript fail (2) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "javascript fail (2) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
ngx.req.read_body()
local args, err = ngx.req.get_post_args(1)
if err == "truncated" or not args or not args["challenge"] then
ngx.log(ngx.WARN, "[ANTIBOT] javascript fail (3) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "javascript fail (3) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
local challenge = args["challenge"]
local check = javascript.check(cookie.get("challenge"), challenge)
if not check then
ngx.log(ngx.WARN, "[ANTIBOT] javascript fail (4) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "javascript fail (4) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
cookie.set({javascript = "ok"})

View File

@@ -1,4 +1,4 @@
location = %ANTIBOT_URI% {
location = {{ ANTIBOT_URI }} {
default_type 'text/html';
@@ -6,11 +6,12 @@ location = %ANTIBOT_URI% {
content_by_lua_block {
local cookie = require "cookie"
local recaptcha = require "recaptcha"
local loggger = require "logger"
if not cookie.is_set("uri") then
ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (1) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "recaptcha fail (1) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
local code = recaptcha.get_code("%ANTIBOT_URI%", "%ANTIBOT_RECAPTCHA_SITEKEY%")
local code = recaptcha.get_code("{{ ANTIBOT_URI }}", "{{ ANTIBOT_RECAPTCHA_SITEKEY }}")
ngx.say(code)
}
}
@@ -19,20 +20,21 @@ location = %ANTIBOT_URI% {
access_by_lua_block {
local cookie = require "cookie"
local recaptcha = require "recaptcha"
local logger = require "logger"
if not cookie.is_set("uri") then
ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (2) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "recaptcha fail (2) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
ngx.req.read_body()
local args, err = ngx.req.get_post_args(1)
if err == "truncated" or not args or not args["token"] then
ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (3) for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "recaptcha fail (3) for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
local token = args["token"]
local check = recaptcha.check(token, "%ANTIBOT_RECAPTCHA_SECRET%")
if check < %ANTIBOT_RECAPTCHA_SCORE% then
ngx.log(ngx.WARN, "[ANTIBOT] recaptcha fail (4) for " .. ngx.var.remote_addr .. " (score = " .. tostring(check) .. ")")
local check = recaptcha.check(token, "{{ ANTIBOT_RECAPTCHA_SECRET }}")
if check < {{ ANTIBOT_RECAPTCHA_SCORE }} then
logger.log(ngx.WARN, "ANTIBOT", "recaptcha fail (4) for " .. ngx.var.remote_addr .. " (score = " .. tostring(check) .. ")")
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
cookie.set({recaptcha = "ok"})

View File

@@ -1,2 +1,2 @@
auth_basic "%AUTH_BASIC_TEXT%";
auth_basic_user_file %NGINX_PREFIX%.htpasswd;
auth_basic "{{ AUTH_BASIC_TEXT }}";
auth_basic_user_file {{ NGINX_PREFIX }}htpasswd;

View File

@@ -1,4 +1,4 @@
location %AUTH_BASIC_LOCATION% {
auth_basic "%AUTH_BASIC_TEXT%";
auth_basic_user_file %NGINX_PREFIX%.htpasswd;
location {{ AUTH_BASIC_LOCATION }} {
auth_basic "{{ AUTH_BASIC_TEXT }}";
auth_basic_user_file {{ NGINX_PREFIX }}htpasswd;
}

View File

@@ -1,4 +1,4 @@
brotli on;
brotli_types %BROTLI_TYPES%;
brotli_comp_level %BROTLI_COMP_LEVEL%;
brotli_min_length %BROTLI_MIN_LENGTH%;
brotli_types {{ BROTLI_TYPES }};
brotli_comp_level {{ BROTLI_COMP_LEVEL }};
brotli_min_length {{ BROTLI_MIN_LENGTH }};

View File

@@ -1,4 +1,6 @@
location ~* \.(%CLIENT_CACHE_EXTENSIONS%)$ {
etag %CLIENT_CACHE_ETAG%;
add_header Cache-Control "%CLIENT_CACHE_CONTROL%";
etag {{ CLIENT_CACHE_ETAG }};
set $cache "";
if ($uri ~* \.({{ CLIENT_CACHE_EXTENSIONS }})$) {
set $cache "{{ CLIENT_CACHE_CONTROL }}";
}
add_header Cache-Control $cache;

View File

@@ -1 +1 @@
more_set_headers "Content-Security-Policy: %CONTENT_SECURITY_POLICY%";
more_set_headers "Content-Security-Policy: {{ CONTENT_SECURITY_POLICY }}";

View File

@@ -1 +1 @@
set_cookie_flag %COOKIE_FLAGS%;
set_cookie_flag {{ COOKIE_FLAGS }}{% if COOKIE_AUTO_SECURE_FLAG == "yes" %} Secure{% endif %};

View File

@@ -1,7 +1,9 @@
listen 0.0.0.0:443 ssl %HTTP2%;
ssl_certificate %HTTPS_CUSTOM_CERT%;
ssl_certificate_key %HTTPS_CUSTOM_KEY%;
listen 0.0.0.0:443 ssl {% if HTTP2 == "yes" %}http2{% endif %};
ssl_certificate {{ HTTPS_CUSTOM_CERT }};
ssl_certificate_key {{ HTTPS_CUSTOM_KEY }};
ssl_protocols TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_session_tickets off;
%STRICT_TRANSPORT_SECURITY%
{% if STRICT_TRANSPORT_SECURITY != "" %}
more_set_headers 'Strict-Transport-Security: {{ STRICT_TRANSPORT_SECURITY }}';
{% endif %}

View File

@@ -1,3 +1,3 @@
if ($host !~ ^(%SERVER_NAME%)$) {
if ($host !~ ^({{ SERVER_NAME.replace(" ", "|") }})$) {
return 444;
}

View File

@@ -1,7 +1,26 @@
error_page %CODE% %PAGE%;
{% if ERRORS != "" %}
{% for element in ERRORS.split(" ") %}
{% set code = element.split("=")[0] %}
{% set page = element.split("=")[1] %}
error_page {{ code }} {{ page }};
location = %PAGE% {
root %ROOT_FOLDER%;
location = {{ page }} {
root {{ ROOT_FOLDER }};
modsecurity off;
internal;
}
{% endfor %}
{% endif %}
{% set default_errors = ["400", "401", "403", "404", "429", "500", "501", "502", "503", "504"] %}
{% for default_error in default_errors %}
{% if not default_error + "=" in ERRORS %}
error_page {{ default_error }} /errors/{{ default_error }}.html;
location = /errors/{{ default_error }}.html {
root /defaults;
modsecurity off;
internal;
}
{% endif %}
{% endfor %}

View File

@@ -1,4 +1,4 @@
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME {{ REMOTE_PHP_PATH }}/$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
@@ -13,7 +13,7 @@ fastcgi_param REQUEST_SCHEME $scheme;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;

View File

@@ -1 +1 @@
more_set_headers "Feature-Policy: %FEATURE_POLICY%";
more_set_headers "Feature-Policy: {{ FEATURE_POLICY }}";

View File

@@ -1,4 +1,4 @@
gzip on;
gzip_comp_level %GZIP_COMP_LEVEL%;
gzip_min_length %GZIP_MIN_LENGTH%;
gzip_types %GZIP_TYPES%;
gzip_comp_level {{ GZIP_COMP_LEVEL }};
gzip_min_length {{ GZIP_MIN_LENGTH }};
gzip_types {{ GZIP_TYPES }};

3
confs/site/htpasswd Normal file
View File

@@ -0,0 +1,3 @@
{% if USE_AUTH_BASIC == "yes" %}
{{ AUTH_BASIC_USER }}:{{ sha512_crypt(AUTH_BASIC_PASSWORD) }}
{% endif %}

View File

@@ -1,12 +1,34 @@
listen 0.0.0.0:%HTTPS_PORT% ssl %HTTP2%;
ssl_certificate %HTTPS_CERT%;
ssl_certificate_key %HTTPS_KEY%;
ssl_protocols %HTTPS_PROTOCOLS%;
listen 0.0.0.0:{{ HTTPS_PORT }} ssl {% if HTTP2 == "yes" %}http2{% endif %};
{% set paths = {"cert": "", "key": ""} %}
{% if AUTO_LETS_ENCRYPT == "yes" %}
{% set x = paths.update({"cert": "/etc/letsencrypt/live/" + FIRST_SERVER + "/fullchain.pem"}) %}
{% set x = paths.update({"key": "/etc/letsencrypt/live/" + FIRST_SERVER + "/privkey.pem"}) %}
{% elif USE_CUSTOM_HTTPS == "yes" %}
{% set x = paths.update({"cert": CUSTOM_HTTPS_CERT}) %}
{% set x = paths.update({"key": CUSTOM_HTTPS_KEY}) %}
{% elif GENERATE_SELF_SIGNED_SSL == "yes" %}
{% if MULTISITE == "yes" %}
{% set x = paths.update({"cert": "/etc/nginx/" + FIRST_SERVER + "/self-cert.pem"}) %}
{% set x = paths.update({"key": "/etc/nginx/" + FIRST_SERVER + "/self-key.pem"}) %}
{% else %}
{% set x = paths.update({"cert": "/etc/nginx/self-cert.pem"}) %}
{% set x = paths.update({"key": "/etc/nginx/self-key.pem"}) %}
{% endif %}
{% endif %}
ssl_certificate {{ paths["cert"] }};
ssl_certificate_key {{ paths["key"] }};
ssl_protocols {{ HTTPS_PROTOCOLS }};
ssl_prefer_server_ciphers on;
ssl_session_tickets off;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m;
%STRICT_TRANSPORT_SECURITY%
%SSL_DHPARAM%
%SSL_CIPHERS%
%LETS_ENCRYPT_WEBROOT%
{% if STRICT_TRANSPORT_SECURITY != "" %}
more_set_headers 'Strict-Transport-Security: {{ STRICT_TRANSPORT_SECURITY }}';
{% endif %}
{% if "TLSv1.2" in HTTPS_PROTOCOLS %}
ssl_dhparam /etc/nginx/dhparam;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
{% endif %}
{% if AUTO_LETS_ENCRYPT %}
include {{ NGINX_PREFIX }}lets-encrypt-webroot.conf;
{% endif %}

View File

@@ -1 +1 @@
limit_conn ddos %LIMIT_CONN_MAX%;
limit_conn ddos {{ LIMIT_CONN_MAX }};

View File

@@ -1,3 +1,3 @@
limit_req_status 429;
limit_req zone=limit burst=%LIMIT_REQ_BURST% nodelay;
limit_req zone=limit burst={{ LIMIT_REQ_BURST }} nodelay;

15
confs/site/log-lua.conf Normal file
View File

@@ -0,0 +1,15 @@
log_by_lua_block {
-- bad behavior
local use_bad_behavior = {% if USE_BAD_BEHAVIOR == "yes" %}true{% else %}false{% endif %}
local behavior = require "behavior"
local bad_behavior_status_codes = {% raw %}{{% endraw %}{% if BAD_BEHAVIOR_STATUS_CODES != "" %}{% set elements = BAD_BEHAVIOR_STATUS_CODES.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
local bad_behavior_threshold = {{ BAD_BEHAVIOR_THRESHOLD }}
local bad_behavior_count_time = {{ BAD_BEHAVIOR_COUNT_TIME }}
local bad_behavior_ban_time = {{ BAD_BEHAVIOR_BAN_TIME }}
if use_bad_behavior then
behavior.count(bad_behavior_status_codes, bad_behavior_threshold, bad_behavior_count_time, bad_behavior_ban_time)
end
}

View File

@@ -1,41 +1,77 @@
set $session_secret %ANTIBOT_SESSION_SECRET%;
{% if ANTIBOT_SESSION_SECRET == "random" %}
set $session_secret {{ random(32) }} ;
{% else %}
set $session_secret {{ ANTIBOT_SESSION_SECRET }};
{% endif %}
set $session_check_addr on;
access_by_lua_block {
local use_lets_encrypt = %USE_LETS_ENCRYPT%
local use_whitelist_ip = %USE_WHITELIST_IP%
local use_whitelist_reverse = %USE_WHITELIST_REVERSE%
local use_user_agent = %USE_USER_AGENT%
local use_referrer = %USE_REFERRER%
local use_country = %USE_COUNTRY%
local use_blacklist_ip = %USE_BLACKLIST_IP%
local use_blacklist_reverse = %USE_BLACKLIST_REVERSE%
local use_dnsbl = %USE_DNSBL%
local use_crowdsec = %USE_CROWDSEC%
local use_antibot_cookie = %USE_ANTIBOT_COOKIE%
local use_antibot_javascript = %USE_ANTIBOT_JAVASCRIPT%
local use_antibot_captcha = %USE_ANTIBOT_CAPTCHA%
local use_antibot_recaptcha = %USE_ANTIBOT_RECAPTCHA%
-- disable checks for internal requests
if ngx.req.is_internal() then
return
end
-- let's encrypt
local use_lets_encrypt = {% if AUTO_LETS_ENCRYPT == "yes" %}true{% else %}false{% endif %}
-- external blacklists
local use_user_agents = {% if BLOCK_USER_AGENT == "yes" %}true{% else %}false{% endif %}
local use_proxies = {% if BLOCK_PROXIES == "yes" %}true{% else %}false{% endif %}
local use_abusers = {% if BLOCK_ABUSERS == "yes" %}true{% else %}false{% endif %}
local use_tor_exit_nodes = {% if BLOCK_TOR_EXIT_NODE == "yes" %}true{% else %}false{% endif %}
local use_referrers = {% if BLOCK_REFERRER == "yes" %}true{% else %}false{% endif %}
-- countries
local use_country = {% if WHITELIST_COUNTRY != "" or BLACKLIST_COUNTRY != "" %}true{% else %}false{% endif %}
-- crowdsec
local use_crowdsec = {% if USE_CROWDSEC == "yes" %}true{% else %}false{% endif %}
-- antibot
local use_antibot_cookie = {% if USE_ANTIBOT == "cookie" %}true{% else %}false{% endif %}
local use_antibot_javascript = {% if USE_ANTIBOT == "javascript" %}true{% else %}false{% endif %}
local use_antibot_captcha = {% if USE_ANTIBOT == "captcha" %}true{% else %}false{% endif %}
local use_antibot_recaptcha = {% if USE_ANTIBOT == "recaptcha" %}true{% else %}false{% endif %}
-- resolvers
local dns_resolvers = {% raw %}{{% endraw %}{% if DNS_RESOLVERS != "" %}{% set elements = DNS_RESOLVERS.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
-- whitelist
local use_whitelist_ip = {% if USE_WHITELIST_IP == "yes" %}true{% else %}false{% endif %}
local use_whitelist_reverse = {% if USE_WHITELIST_REVERSE == "yes" %}true{% else %}false{% endif %}
local whitelist_ip_list = {% raw %}{{% endraw %}{% if WHITELIST_IP_LIST != "" %}{% set elements = WHITELIST_IP_LIST.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
local whitelist_reverse_list = {% raw %}{{% endraw %}{% if WHITELIST_REVERSE_LIST != "" %}{% set elements = WHITELIST_REVERSE_LIST.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
-- blacklist
local use_blacklist_ip = {% if USE_BLACKLIST_IP == "yes" %}true{% else %}false{% endif %}
local use_blacklist_reverse = {% if USE_BLACKLIST_REVERSE == "yes" %}true{% else %}false{% endif %}
local blacklist_ip_list = {% raw %}{{% endraw %}{% if BLACKLIST_IP_LIST != "" %}{% set elements = BLACKLIST_IP_LIST.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
local blacklist_reverse_list = {% raw %}{{% endraw %}{% if BLACKLIST_REVERSE_LIST != "" %}{% set elements = BLACKLIST_REVERSE_LIST.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
-- dnsbl
local use_dnsbl = {% if USE_DNSBL == "yes" %}true{% else %}false{% endif %}
local dnsbl_list = {% raw %}{{% endraw %}{% if DNSBL_LIST != "" %}{% set elements = DNSBL_LIST.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
-- bad behavior
local use_bad_behavior = {% if USE_BAD_BEHAVIOR == "yes" %}true{% else %}false{% endif %}
-- include LUA code
local whitelist = require "whitelist"
local blacklist = require "blacklist"
local dnsbl = require "dnsbl"
local cookie = require "cookie"
local javascript = require "javascript"
local captcha = require "captcha"
local recaptcha = require "recaptcha"
local whitelist = require "whitelist"
local blacklist = require "blacklist"
local dnsbl = require "dnsbl"
local cookie = require "cookie"
local javascript = require "javascript"
local captcha = require "captcha"
local recaptcha = require "recaptcha"
local iputils = require "resty.iputils"
local behavior = require "behavior"
local logger = require "logger"
-- user variables
local antibot_uri = "%ANTIBOT_URI%"
local whitelist_user_agent = {%WHITELIST_USER_AGENT%}
-- check if it's let's encrypt bot
if use_lets_encrypt and string.match(ngx.var.request_uri, "^/.well-known/acme-challenge/") then
ngx.exit(ngx.OK)
end
local antibot_uri = "{{ ANTIBOT_URI }}"
local whitelist_user_agent = {% raw %}{{% endraw %}{% if WHITELIST_USER_AGENT != "" %}{% set elements = WHITELIST_USER_AGENT.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
local whitelist_uri = {% raw %}{{% endraw %}{% if WHITELIST_URI != "" %}{% set elements = WHITELIST_URI.split(" ") %}{% for i in range(0, elements|length) %}"{{ elements[i] }}"{% if i < elements|length-1 %},{% endif %}{% endfor %}{% endif %}{% raw %}}{% endraw %}
-- check if already in whitelist cache
if use_whitelist_ip and whitelist.ip_cached_ok() then
@@ -60,66 +96,144 @@ end
-- check if IP is whitelisted (only if not in cache)
if use_whitelist_ip and not whitelist.ip_cached() then
if whitelist.check_ip() then
if whitelist.check_ip(whitelist_ip_list) then
ngx.exit(ngx.OK)
end
end
-- check if reverse is whitelisted (only if not in cache)
if use_whitelist_reverse and not whitelist.reverse_cached() then
if whitelist.check_reverse() then
if whitelist.check_reverse(whitelist_reverse_list) then
ngx.exit(ngx.OK)
end
end
-- check if URI is whitelisted
for k, v in pairs(whitelist_uri) do
if ngx.var.request_uri == v then
logger.log(ngx.NOTICE, "WHITELIST", "URI " .. v .. " is whitelisted")
ngx.exit(ngx.OK)
end
end
-- check if it's certbot
if use_lets_encrypt and string.match(ngx.var.request_uri, "^/.well-known/acme-challenge/") then
logger.log(ngx.INFO, "LETSENCRYPT", "got a visit from Let's Encrypt")
ngx.exit(ngx.OK)
end
-- check if IP is blacklisted (only if not in cache)
if use_blacklist_ip and not blacklist.ip_cached() then
if blacklist.check_ip() then
if blacklist.check_ip(blacklist_ip_list) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- check if reverse is blacklisted (only if not in cache)
if use_blacklist_reverse and not blacklist.reverse_cached() then
if blacklist.check_reverse() then
if blacklist.check_reverse(blacklist_reverse_list, dns_resolvers) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- check if IP is banned because of "bad behavior"
if use_bad_behavior and behavior.is_banned() then
logger.log(ngx.WARN, "BEHAVIOR", "IP " .. ngx.var.remote_addr .. " is banned because of bad behavior")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
-- check if IP is in proxies list
if use_proxies then
local value, flags = ngx.shared.proxies_data:get(iputils.ip2bin(ngx.var.remote_addr))
if value ~= nil then
logger.log(ngx.WARN, "PROXIES", "IP " .. ngx.var.remote_addr .. " is in proxies list")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- check if IP is in abusers list
if use_abusers then
local value, flags = ngx.shared.abusers_data:get(iputils.ip2bin(ngx.var.remote_addr))
if value ~= nil then
logger.log(ngx.WARN, "ABUSERS", "IP " .. ngx.var.remote_addr .. " is in abusers list")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- check if IP is in TOR exit nodes list
if use_tor_exit_nodes then
local value, flags = ngx.shared.tor_exit_nodes_data:get(iputils.ip2bin(ngx.var.remote_addr))
if value ~= nil then
logger.log(ngx.WARN, "TOR", "IP " .. ngx.var.remote_addr .. " is in TOR exit nodes list")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- check if user-agent is allowed
if use_user_agent and ngx.var.bad_user_agent == "yes" then
local headers = ngx.req.get_headers()
local ua = headers["User-Agent"]
if not whitelist_user_agent ~= "" then
local k_ua_white, v_ua_white = next(whitelist_user_agent, nil)
while v_ua_white do
local rst_whitelist = string.match(ua, v_ua_white)
if rst_whitelist ~= nil and rst_whitelist ~= "" then
ngx.log(ngx.WARN, "[ALLOW] User-Agent " .. ngx.var.http_user_agent .. " is whitelisted")
ngx.exit(ngx.OK)
end
k_ua_white, v_ua_white = next(whitelist_user_agent, k_ua_white)
if use_user_agents and ngx.var.http_user_agent ~= nil then
local whitelisted = false
for k, v in pairs(whitelist_user_agent) do
if string.match(ngx.var.http_user_agent, v) then
logger.log(ngx.NOTICE, "WHITELIST", "User-Agent " .. ngx.var.http_user_agent .. " is whitelisted")
whitelisted = true
break
end
end
if not whitelisted then
local value, flags = ngx.shared.user_agents_cache:get(ngx.var.http_user_agent)
if value == nil then
local patterns = ngx.shared.user_agents_data:get_keys(0)
for i, pattern in ipairs(patterns) do
if string.match(ngx.var.http_user_agent, pattern) then
value = "ko"
ngx.shared.user_agents_cache:set(ngx.var.http_user_agent, "ko", 86400)
break
end
end
if value == nil then
value = "ok"
ngx.shared.user_agents_cache:set(ngx.var.http_user_agent, "ok", 86400)
end
end
if value == "ko" then
logger.log(ngx.WARN, "USER-AGENT", "User-Agent " .. ngx.var.http_user_agent .. " is blacklisted")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
ngx.log(ngx.WARN, "[BLOCK] User-Agent " .. ngx.var.http_user_agent .. " is blacklisted")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
-- check if referrer is allowed
if use_referrer and ngx.var.bad_referrer == "yes" then
ngx.log(ngx.WARN, "[BLOCK] Referrer " .. ngx.var.http_referer .. " is blacklisted")
ngx.exit(ngx.HTTP_FORBIDDEN)
if use_referrer and ngx.var.http_referer ~= nil then
local value, flags = ngx.shared.referrers_cache:get(ngx.var.http_referer)
if value == nil then
local patterns = ngx.shared.referrers_data:get_keys(0)
for i, pattern in ipairs(patterns) do
if string.match(ngx.var.http_referer, pattern) then
value = "ko"
ngx.shared.referrers_cache:set(ngx.var.http_referer, "ko", 86400)
break
end
end
if value == nil then
value = "ok"
ngx.shared.referrers_cache:set(ngx.var.http_referer, "ok", 86400)
end
end
if value == "ko" then
logger.log(ngx.WARN, "REFERRER", "Referrer " .. ngx.var.http_referer .. " is blacklisted")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- check if country is allowed
if use_country and ngx.var.allowed_country == "no" then
ngx.log(ngx.WARN, "[BLOCK] Country of " .. ngx.var.remote_addr .. " is blacklisted")
logger.log(ngx.WARN, "COUNTRY", "Country of " .. ngx.var.remote_addr .. " is blacklisted")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
-- check if IP is in DNSBLs (only if not in cache)
if use_dnsbl and not dnsbl.cached() then
if dnsbl.check() then
if dnsbl.check(dnsbl_list, dns_resolvers) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
@@ -128,22 +242,22 @@ end
if use_crowdsec then
local ok, err = require "crowdsec.CrowdSec".allowIp(ngx.var.remote_addr)
if ok == nil then
ngx.log(ngx.ERR, "[Crowdsec] " .. err)
logger.log(ngx.ERR, "CROWDSEC", err)
end
if not ok then
ngx.log(ngx.ERR, "[Crowdsec] denied '" .. ngx.var.remote_addr .. "'")
logger.log(ngx.WARN, "CROWDSEC", "denied " .. ngx.var.remote_addr)
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
-- cookie check
if use_antibot_cookie then
if use_antibot_cookie and ngx.var.uri ~= "/favicon.ico" then
if not cookie.is_set("uri") then
if ngx.var.request_uri ~= antibot_uri then
cookie.set({uri = ngx.var.request_uri})
return ngx.redirect(antibot_uri)
end
ngx.log(ngx.WARN, "[ANTIBOT] cookie fail for " .. ngx.var.remote_addr)
logger.log(ngx.WARN, "ANTIBOT", "cookie fail for " .. ngx.var.remote_addr)
return ngx.exit(ngx.HTTP_FORBIDDEN)
else
if ngx.var.request_uri == antibot_uri then
@@ -153,7 +267,7 @@ if use_antibot_cookie then
end
-- javascript check
if use_antibot_javascript then
if use_antibot_javascript and ngx.var.uri ~= "/favicon.ico" then
if not cookie.is_set("javascript") then
if ngx.var.request_uri ~= antibot_uri then
cookie.set({uri = ngx.var.request_uri, challenge = javascript.get_challenge()})
@@ -163,7 +277,7 @@ if use_antibot_javascript then
end
-- captcha check
if use_antibot_captcha then
if use_antibot_captcha and ngx.var.uri ~= "/favicon.ico" then
if not cookie.is_set("captcha") then
if ngx.var.request_uri ~= antibot_uri then
cookie.set({uri = ngx.var.request_uri})
@@ -173,7 +287,7 @@ if use_antibot_captcha then
end
-- recaptcha check
if use_antibot_recaptcha then
if use_antibot_recaptcha and ngx.var.uri ~= "/favicon.ico" then
if not cookie.is_set("recaptcha") then
if ngx.var.request_uri ~= antibot_uri then
cookie.set({uri = ngx.var.request_uri})
@@ -182,12 +296,23 @@ if use_antibot_recaptcha then
end
end
-- plugins check
local plugins, flags = ngx.shared.plugins_data:get("plugins")
if plugins ~= nil then
for plugin_id in string.gmatch(plugins, "%w+") do
local plugin = require(plugin_id .. "/" .. plugin_id)
plugin.check()
end
end
ngx.exit(ngx.OK)
}
%INCLUDE_ANTIBOT_JAVASCRIPT%
%INCLUDE_ANTIBOT_CAPTCHA%
%INCLUDE_ANTIBOT_RECAPTCHA%
{% if USE_ANTIBOT == "javascript" %}
include {{ NGINX_PREFIX }}antibot-javascript.conf;
{% elif USE_ANTIBOT == "captcha" %}
include {{ NGINX_PREFIX }}antibot-captcha.conf;
{% elif USE_ANTIBOT == "recaptcha" %}
include {{ NGINX_PREFIX }}antibot-recaptcha.conf;
{% endif %}

View File

@@ -1,4 +0,0 @@
SecUploadDir /tmp
SecUploadKeepFiles On
SecRule FILES_TMPNAMES "@inspectFile /opt/scripts/clamav.sh" \
"phase:2,t:none,deny,msg:'Virus found in uploaded file',id:'399999'"

View File

@@ -49,18 +49,30 @@ SecResponseBodyLimit 524288
SecResponseBodyLimitAction ProcessPartial
# log usefull stuff
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
SecAuditEngine {{ MODSECURITY_SEC_AUDIT_ENGINE }}
SecAuditLogType Serial
SecAuditLog /var/log/nginx/modsec_audit.log
# scan uploaded files with clamv
%USE_CLAMAV_UPLOAD%
# include OWASP CRS configuration
{% if USE_MODSECURITY_CRS == "yes" %}
include /opt/owasp/crs.conf
# custom CRS configurations before loading rules (exclusions)
{% if is_custom_conf("/modsec-crs-confs") %}
include /modsec-crs-confs/*.conf
{% endif %}
{% if MULTISITE == "yes" and is_custom_conf("/modsec-crs-confs/" + FIRST_SERVER) %}
include /modsec-crs-confs/{{ FIRST_SERVER }}/*.conf
{% endif %}
# include OWASP CRS rules
%MODSECURITY_INCLUDE_CRS%
%MODSECURITY_INCLUDE_CUSTOM_CRS%
%MODSECURITY_INCLUDE_CRS_RULES%
include /opt/owasp/crs/*.conf
{% endif %}
# include custom rules
%MODSECURITY_INCLUDE_CUSTOM_RULES%
# custom rules after loading the CRS
{% if is_custom_conf("/modsec-confs") %}
include /modsec-confs/*.conf
{% endif %}
{% if MULTISITE == "yes" and is_custom_conf("/modsec-confs/" + FIRST_SERVER) %}
include /modsec-confs/{{ FIRST_SERVER }}/*.conf
{% endif %}

View File

@@ -1,2 +1,2 @@
modsecurity on;
modsecurity_rules_file %MODSEC_RULES_FILE%;
modsecurity_rules_file {{ NGINX_PREFIX }}modsecurity-rules.conf;

View File

@@ -1,4 +1,4 @@
open_file_cache %OPEN_FILE_CACHE%;
open_file_cache_errors %OPEN_FILE_CACHE_ERRORS%;
open_file_cache_min_uses %OPEN_FILE_CACHE_MIN_USES%;
open_file_cache_valid %OPEN_FILE_CACHE_VALID%;
open_file_cache {{ OPEN_FILE_CACHE }};
open_file_cache_errors {{ OPEN_FILE_CACHE_ERRORS }};
open_file_cache_min_uses {{ OPEN_FILE_CACHE_MIN_USES }};
open_file_cache_valid {{ OPEN_FILE_CACHE_VALID }};

View File

@@ -1 +1 @@
more_set_headers "Permissions-Policy: %PERMISSIONS_POLICY%";
more_set_headers "Permissions-Policy: {{ PERMISSIONS_POLICY }}";

View File

@@ -1,4 +1,4 @@
location ~ \.php$ {
fastcgi_pass %REMOTE_PHP%:9000;
fastcgi_pass {{ REMOTE_PHP }}:9000;
fastcgi_index index.php;
}

View File

@@ -1,7 +1,11 @@
proxy_cache proxycache;
proxy_cache_methods %PROXY_CACHE_METHODS%;
proxy_cache_min_uses %PROXY_CACHE_MIN_USES%;
proxy_cache_key %PROXY_CACHE_KEY%;
proxy_no_cache %PROXY_NO_CACHE%;
proxy_cache_bypass %PROXY_CACHE_BYPASS%;
%PROXY_CACHE_VALID%
proxy_cache_methods {{ PROXY_CACHE_METHODS }};
proxy_cache_min_uses {{ PROXY_CACHE_MIN_USES }};
proxy_cache_key {{ PROXY_CACHE_KEY }};
proxy_no_cache {{ PROXY_NO_CACHE }};
proxy_cache_bypass {{ PROXY_CACHE_BYPASS }};
{% if PROXY_CACHE_VALID != "" %}
{% for element in PROXY_CACHE_VALID.split(" ") %}
proxy_cache_valid {{ element.split("=")[0] }} {{ element.split("=")[1] }};
{% endfor %}
{% endif %}

View File

@@ -1,4 +1,8 @@
%PROXY_REAL_IP_FROM%
real_ip_header %PROXY_REAL_IP_HEADER%;
real_ip_recursive %PROXY_REAL_IP_RECURSIVE%;
{% if PROXY_REAL_IP_FROM != "" %}
{% for element in PROXY_REAL_IP_FROM.split(" ") %}
set_real_ip_from {{ element }};
{% endfor %}
{% endif %}
real_ip_header {{ PROXY_REAL_IP_HEADER }};
real_ip_recursive {{ PROXY_REAL_IP_RECURSIVE }};

View File

@@ -1 +1 @@
more_set_headers "Referrer-Policy: %REFERRER_POLICY%";
more_set_headers "Referrer-Policy: {{ REFERRER_POLICY }}";

View File

@@ -1,6 +1,25 @@
location %REVERSE_PROXY_URL% {
proxy_pass %REVERSE_PROXY_HOST%;
%REVERSE_PROXY_HEADERS%
%REVERSE_PROXY_WS%
%REVERSE_PROXY_CUSTOM_HEADERS%
}
{% if USE_REVERSE_PROXY == "yes" %}
{% for k, v in all.items() %}
{% if k.startswith("REVERSE_PROXY_URL") and v != "" %}
{% set url = v %}
{% set host = all[k.replace("URL", "HOST")] if k.replace("URL", "HOST") in all else "" %}
{% set ws = all[k.replace("URL", "WS")] if k.replace("URL", "WS") in all else "" %}
{% set headers = all[k.replace("URL", "HEADERS")] if k.replace("URL", "HEADERS") in all else "" %}
location {{ url }} {% raw %}{{% endraw %}
etag off;
proxy_pass {{ host }};
include {{ NGINX_PREFIX }}reverse-proxy-headers.conf;
{% if ws == "yes" %}
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
{% endif %}
{% if headers != "" %}
{% for header in headers.split(";") %}
proxy_set_header {{ header }};
{% endfor %}
{% endif %}
{% raw %}}{% endraw %}
{% endif %}
{% endfor %}
{% endif %}

View File

@@ -1,3 +1,3 @@
root %ROOT_FOLDER%;
root {{ ROOT_FOLDER }};
index index.html index.php;
try_files $uri $uri/ =404;

View File

@@ -1,45 +1,177 @@
%PRE_SERVER_CONF%
# custom config before server block
include /pre-server-confs/*.conf;
{% if MULTISITE == "yes" %}
include /pre-server-confs/{{ FIRST_SERVER }}/*.conf;
{% endif %}
server {
%FASTCGI_PATH%
%SERVER_CONF%
%PROXY_REAL_IP%
%MAIN_LUA%
%USE_MODSECURITY%
%LISTEN_HTTP%
%USE_HTTPS%
%REDIRECT_HTTP_TO_HTTPS%
server_name %SERVER_NAME%;
%DISABLE_DEFAULT_SERVER%
%SERVE_FILES%
if ($request_method !~ ^(%ALLOWED_METHODS%)$)
{
# FastCGI variables
{% if REMOTE_PHP != "" %}
include {{ NGINX_PREFIX }}fastcgi.conf;
{% endif %}
# custom config
include /server-confs/*.conf;
{% if MULTISITE == "yes" %}
include /server-confs/{{ FIRST_SERVER }}/*.conf;
{% endif %}
# proxy real IP
{% if PROXY_REAL_IP == "yes" %}
include {{ NGINX_PREFIX }}proxy-real-ip.conf;
{% endif %}
# include LUA files
include {{ NGINX_PREFIX }}main-lua.conf;
include {{ NGINX_PREFIX }}log-lua.conf;
# ModSecurity
{% if USE_MODSECURITY == "yes" %}
include {{ NGINX_PREFIX }}modsecurity.conf;
{% endif %}
# HTTP listen
{% if LISTEN_HTTP == "yes" %}
listen 0.0.0.0:{{ HTTP_PORT }};
{% endif %}
# HTTPS listen + config
{% if AUTO_LETS_ENCRYPT == "yes" or USE_CUSTOM_HTTPS == "yes" or GENERATE_SELF_SIGNED_SSL == "yes" %}
include {{ NGINX_PREFIX }}https.conf;
{% endif %}
# HTTP to HTTPS
{% if REDIRECT_HTTP_TO_HTTPS == "yes" %}
include {{ NGINX_PREFIX }}redirect-http-to-https.conf;
{% endif %}
# server name (vhost)
server_name {{ SERVER_NAME }};
# disable default server
{% if DISABLE_DEFAULT_SERVER == "yes" and MULTISITE != "yes" %}
include {{ NGINX_PREFIX }}disable-default-server.conf;
{% endif %}
# serve local files
{% if SERVE_FILES == "yes" %}
include {{ NGINX_PREFIX }}serve-files.conf;
{% endif %}
# allowed HTTP methods
if ($request_method !~ ^({{ ALLOWED_METHODS }})$) {
return 405;
}
%LIMIT_REQ%
%LIMIT_CONN%
%AUTH_BASIC%
%REMOVE_HEADERS%
%X_FRAME_OPTIONS%
%X_XSS_PROTECTION%
%X_CONTENT_TYPE_OPTIONS%
%CONTENT_SECURITY_POLICY%
%REFERRER_POLICY%
%FEATURE_POLICY%
%PERMISSIONS_POLICY%
%BLOCK_TOR_EXIT_NODE%
%BLOCK_PROXIES%
%BLOCK_ABUSERS%
%COOKIE_FLAGS%
%ERRORS%
%USE_FAIL2BAN%
%USE_CLIENT_CACHE%
%USE_GZIP%
%USE_BROTLI%
client_max_body_size %MAX_CLIENT_SIZE%;
server_tokens %SERVER_TOKENS%;
%USE_OPEN_FILE_CACHE%
%USE_PROXY_CACHE%
%USE_REVERSE_PROXY%
%USE_PHP%
# requests limiting
{% if USE_LIMIT_REQ == "yes" %}
include {{ NGINX_PREFIX }}limit-req.conf;
{% endif %}
# connections limiting
{% if USE_LIMIT_CONN == "yes" %}
include {{ NGINX_PREFIX }}limit-conn.conf;
{% endif %}
# auth basic
{% if USE_AUTH_BASIC == "yes" %}
{% if AUTH_BASIC_LOCATION == "sitewide" %}
include {{ NGINX_PREFIX }}auth-basic-sitewide.conf;
{% else %}
include {{ NGINX_PREFIX }}auth-basic.conf;
{% endif %}
{% endif %}
# remove headers
{% if REMOVE_HEADERS != "" %}
{% for header in REMOVE_HEADERS.split(" ") %}
more_clear_headers '{{ header }}';
{% endfor %}
{% endif %}
# X-Frame-Option header
{% if X_FRAME_OPTIONS != "" %}
include {{ NGINX_PREFIX }}x-frame-options.conf;
{% endif %}
# X-XSS-Protection header
{% if X_XSS_PROTECTION != "" %}
include {{ NGINX_PREFIX }}x-xss-protection.conf;
{% endif %}
# X-Content-Type header
{% if X_CONTENT_TYPE_OPTIONS != "" %}
include {{ NGINX_PREFIX }}x-content-type-options.conf;
{% endif %}
# Content-Security-Policy header
{% if CONTENT_SECURITY_POLICY != "" %}
include {{ NGINX_PREFIX }}content-security-policy.conf;
{% endif %}
# Referrer-Policy header
{% if REFERRER_POLICY != "" %}
include {{ NGINX_PREFIX }}referrer-policy.conf;
{% endif %}
# Feature-Policy header
{% if FEATURE_POLICY != "" %}
include {{ NGINX_PREFIX }}feature-policy.conf;
{% endif %}
# Permissions-Policy header
{% if PERMISSIONS_POLICY != "" %}
include {{ NGINX_PREFIX }}permissions-policy.conf;
{% endif %}
# cookie flags
{% if COOKIE_FLAGS != "" %}
include {{ NGINX_PREFIX }}cookie-flags.conf;
{% endif %}
# custom errors
include {{ NGINX_PREFIX }}error.conf;
# client caching
{% if USE_CLIENT_CACHE == "yes" %}
include {{ NGINX_PREFIX }}client-cache.conf;
{% endif %}
# gzip compression
{% if USE_GZIP == "yes" %}
include {{ NGINX_PREFIX }}gzip.conf;
{% endif %}
# brotli compression
{% if USE_BROTLI == "yes" %}
include {{ NGINX_PREFIX }}brotli.conf;
{% endif %}
# maximum body size
client_max_body_size {{ MAX_CLIENT_SIZE }};
# enable/disable showing version
server_tokens {{ SERVER_TOKENS }};
# open file caching
{% if USE_OPEN_FILE_CACHE == "yes" %}
include {{ NGINX_PREFIX }}open-file-cache.conf;
{% endif %}
# proxy caching
{% if USE_PROXY_CACHE == "yes" %}
include {{ NGINX_PREFIX }}proxy-cache.conf;
{% endif %}
# reverse proxy
{% if USE_REVERSE_PROXY == "yes" %}
include {{ NGINX_PREFIX }}reverse-proxy.conf;
{% endif %}
# remote PHP
{% if REMOTE_PHP != "" %}
include {{ NGINX_PREFIX }}php.conf;
{% endif %}
}

View File

@@ -1 +1 @@
more_set_headers "X-Content-Type-Options: %X_CONTENT_TYPE_OPTIONS%";
more_set_headers "X-Content-Type-Options: {{ X_CONTENT_TYPE_OPTIONS }}";

View File

@@ -1 +1 @@
more_set_headers "X-Frame-Options: %X_FRAME_OPTIONS%";
more_set_headers "X-Frame-Options: {{ X_FRAME_OPTIONS }}";

View File

@@ -1 +1 @@
more_set_headers "X-XSS-Protection: %X_XSS_PROTECTION%";
more_set_headers "X-XSS-Protection: {{ X_XSS_PROTECTION }}";

23
defaults/errors/400.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>400 - Bad Request</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>400 - Bad Request</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/401.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>401 - Unauthorized</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>401 - Unauthorized</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/403.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>403 - Forbidden</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>403 - Forbidden</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/404.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>404 - Not Found</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>404 - Not Found</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/429.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>429 - Too Many Requests</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>429 - Too Many Requests</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/500.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>500 - Internal Server Error</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>500 - Internal Server Error</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/501.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>501 - Not Implemented</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>501 - Not Implemented</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/502.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>502 - Bad Gateway</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>502 - Bad Gateway</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

23
defaults/errors/503.html Normal file
View File

@@ -0,0 +1,23 @@
<html>
<head>
<title>503 - Service Unavailable</title>
<style>
body {
background-color: #1d70b7;
}
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<div class="centered" style="color: white;">
<h1>503 - Service Unavailable</h1>
&#128737;&#65039; this website is protected with <a href="https://github.com/bunkerity/bunkerized-nginx" target="_blank">bunkerized-nginx</a> &#128737;&#65039;
</div>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show More