├── .gitignore
├── requirements.txt
├── python-package
├── MANIFEST.in
├── src
│ └── cf_shield
│ │ ├── __init__.py
│ │ └── main.py
├── pyproject.toml
├── README.md
└── LICENSE
├── README.md
├── LICENSE
└── main.py
/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sakura-sx/cf-shield/HEAD/.gitignore
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | psutil
2 | cloudflare
3 | python-dotenv
4 | discord-webhook
5 | requests
6 | logging
7 | colorlog
8 | slack_sdk
9 | ntfy
--------------------------------------------------------------------------------
/python-package/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md
2 | include LICENSE
3 | recursive-include src *.py
4 | global-exclude *.pyc
5 | global-exclude __pycache__
6 | global-exclude .git*
7 | global-exclude deploy.py
--------------------------------------------------------------------------------
/python-package/src/cf_shield/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | CF-Shield
3 |
4 | A Python package for detecting DDoS attacks and enabling security measures
5 | on Cloudflare automatically by monitoring CPU usage.
6 | """
7 |
8 | __version__ = "0.1.0"
9 | __author__ = "Sakura-sx"
10 | __email__ = "sakura@voxga.xyz"
11 |
12 | from .main import run, main, setup
13 |
14 | __all__ = ["run", "main", "setup"]
--------------------------------------------------------------------------------
/python-package/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=61.0", "wheel"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "cf-shield"
7 | version = "0.2.0"
8 | authors = [
9 | {name = "Sakura-sx", email = "sakura@voxga.xyz"},
10 | ]
11 | description = "CF-Shield is a Python script for detecting DDoS attacks and enabling security measures on Cloudflare automatically."
12 | readme = "README.md"
13 | requires-python = ">=3.8"
14 | classifiers = [
15 | "Development Status :: 5 - Production/Stable",
16 | "Intended Audience :: System Administrators",
17 | "Intended Audience :: Developers",
18 | "Operating System :: OS Independent",
19 | "Programming Language :: Python :: 3",
20 | "Programming Language :: Python :: 3.8",
21 | "Programming Language :: Python :: 3.9",
22 | "Programming Language :: Python :: 3.10",
23 | "Programming Language :: Python :: 3.11",
24 | "Programming Language :: Python :: 3.12",
25 | "Topic :: Internet",
26 | "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
27 | "Topic :: System :: Monitoring",
28 | "Topic :: System :: Systems Administration",
29 | ]
30 | dependencies = [
31 | "psutil",
32 | "cloudflare",
33 | "python-dotenv",
34 | "discord-webhook",
35 | "colorlog",
36 | "requests",
37 | "logging",
38 | "slack_sdk"
39 | ]
40 | license = "GPL-3.0"
41 | license-files = ["LICENSE"]
42 |
43 | [project.urls]
44 | Homepage = "https://github.com/Sakura-sx/cf-shield"
45 | Issues = "https://github.com/Sakura-sx/cf-shield/issues"
46 | Repository = "https://github.com/Sakura-sx/cf-shield"
47 |
48 | [project.scripts]
49 | cf-shield = "cf_shield.main:run"
50 |
51 | [tool.setuptools.packages.find]
52 | where = ["src"]
53 |
54 | [tool.setuptools.package-dir]
55 | "" = "src"
--------------------------------------------------------------------------------
/python-package/README.md:
--------------------------------------------------------------------------------
1 | # CF-Shield
2 |
3 | CF-Shield is a Python package for detecting DDoS attacks and enabling security measures on Cloudflare automatically.
4 |
5 | ## Installation
6 |
7 | Install CF-Shield using pip:
8 |
9 | ```bash
10 | pip install cf-shield
11 | ```
12 |
13 | First, you will need to get your Cloudflare email, API token, zone ID, and account ID.
14 |
15 | After installation, run:
16 |
17 | ```bash
18 | cf-shield
19 | ```
20 |
21 | When running the script for the first time, it will ask you for your Cloudflare email, API token, zone ID, and account ID. More info on [Setup](#setup).
22 |
23 | ## Setup
24 | To setup the script, you will need to run the script and follow the prompts. Here you have a list of what the script will ask you for and what you need to do. The prompts with `default:` are optional and will be set to the default value if you don't enter anything.
25 |
26 | The full setup looks like this:
27 |
28 | ```
29 | /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$
30 | /$$__ $$| $$_____/ /$$__ $$| $$ |__/ | $$ | $$
31 | | $$ \__/| $$ | $$ \__/| $$$$$$$ /$$ /$$$$$$ | $$ /$$$$$$$
32 | | $$ | $$$$$ /$$$$$$| $$$$$$ | $$__ $$| $$ /$$__ $$| $$ /$$__ $$
33 | | $$ | $$__/|______/ \____ $$| $$ \ $$| $$| $$$$$$$$| $$| $$ | $$
34 | | $$ $$| $$ /$$ \ $$| $$ | $$| $$| $$_____/| $$| $$ | $$
35 | | $$$$$$/| $$ | $$$$$$/| $$ | $$| $$| $$$$$$$| $$| $$$$$$$
36 | \______/ |__/ \______/ |__/ |__/|__/ \_______/|__/ \_______/
37 |
38 |
39 |
40 |
41 | Welcome to CF-Shield, we will now set it up for you.
42 | What's the domain(s) you want to use? (e.g. "example.com,www.example.com" or "example.com")
43 | example.com
44 | What's the email you used to sign up for Cloudflare? (e.g. example@example.com)
45 | example@example.com
46 | Please create an API token and copy it here (e.g. aK-MaF3oyTrPDD8YoNBlvqo0ous7BOeSA7te84OR)
47 | aK-MaF3oyTrPDD8YoNBlvqo0ous7BOeSA7te84OR
48 | Please copy the zone ID from the URL of your Cloudflare dashboard (e.g. 1b7c0e3d41f09ceb9cbcde6b0c7bc819)
49 | 1b7c0e3d41f09ceb9cbcde6b0c7bc819
50 | Please copy the account ID from the URL of your Cloudflare dashboard (e.g. 6dead821d9eb4c42f8a8dda399651660)
51 | 6dead821d9eb4c42f8a8dda399651660
52 | Please enter the CPU usage threshold in percentage (default: 80)
53 | 80
54 | What's the challenge type you want to use? (default: managed_challenge, options: managed_challenge, js_challenge, challenge)
55 | managed_challenge
56 | If you want to use a Discord webhook, please enter the webhook URL (default: None)
57 | https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz
58 | If you want to use a Telegram bot, please enter the bot token (default: None)
59 | 1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ
60 | Please enter the chat ID for the telegram bot (default: None)
61 | 1234567890
62 | How many seconds do you want to wait before disabling the challenge rule? (default: 30)
63 | 30
64 | Setup successful!
65 | Ruleset ID: abacebd975b04e398fe02ba19614aa8b
66 | Rule ID: e65dd32a32874c0aa3339af385ca95db
67 | Saving configuration to .env file...
68 | Configuration saved successfully!
69 | Setup complete! Starting monitoring...
70 | ```
71 |
72 | ### 1. Domains
73 | `What's the domain(s) you want to use? (e.g. "example.com,www.example.com" or "example.com" or "all")`
74 |
75 | This is the domain(s) you want to use. You can add multiple domains by separating them with a comma. The domains must be on the same [Zone](https://developers.cloudflare.com/fundamentals/concepts/accounts-and-zones/#zones) (meaning a single WAF rule can be applied to all of them).
76 |
77 | If you want to use all domains in the zone, you can enter `all`.
78 |
79 | If you change this after the inital setup, you will need to remove the rule from the dashboard and run the script again.
80 |
81 | ### 2. Email
82 | `What's the email you used to sign up for Cloudflare? (e.g. example@example.com)`
83 |
84 | This must be the email you used to sign up for Cloudflare. You can find it [here](https://dash.cloudflare.com/profile).
85 |
86 | ### 3. API Token
87 | `Please create an API token and copy it here (e.g. aK-MaF3oyTrPDD8YoNBlvqo0ous7BOeSA7te84OR)`
88 |
89 | This is the API token you need to create. You can create it [here](https://dash.cloudflare.com/profile/api-tokens). There is a guide [here](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/). You need to create a token with `Zone WAF Write` permissions. It should be 40 characters long and only contain letters, numbers and dashes.
90 |
91 | ### 4. Zone ID
92 | `Please copy the zone ID from the URL of your Cloudflare dashboard (e.g. 1b7c0e3d41f09ceb9cbcde6b0c7bc819)`
93 |
94 | This is the zone ID you need to copy from the URL of your Cloudflare dashboard. You can find it [here](https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/#copy-your-zone-id). It should be 32 characters long and only contain letters and numbers.
95 |
96 | ### 5. Account ID
97 | `Please copy the account ID from the URL of your Cloudflare dashboard (e.g. 6dead821d9eb4c42f8a8dda399651660)`
98 |
99 | The account ID can be found below the zone ID. It should not be the same as the zone ID. If you can't find it, there is more info [here](https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/#copy-your-account-id). It should be 32 characters long and only contain letters and numbers.
100 |
101 | #### This was the last prompt you could not set blank. After setting this you can leave blank the other prompts.
102 |
103 | ### 6. CPU Threshold
104 | `Please enter the CPU usage threshold in percentage (default: 80)`
105 |
106 | This is the CPU usage threshold you want to use. The script will enable the challenge rule if the CPU usage is greater than this threshold. It should be a number between 0 and 100. It is advised to set it to a value between 50 and 90 depending on your server's performance and average load.
107 |
108 | ### 7. Challenge Type
109 | `What's the challenge type you want to use? (default: managed_challenge, options: managed_challenge, js_challenge, challenge)`
110 |
111 | This is the challenge type you want to use. You can choose between `managed_challenge`, `js_challenge` and `challenge`.
112 |
113 | `js_challenge` is a challenge that uses JavaScript to detect bots. It is the fastest challenge type to load, but it is also not as effective as `challenge` or `managed_challenge`.
114 |
115 | `challenge` is a challenge that uses a CAPTCHA to detect bots, it was the first challenge type to be released by Cloudflare. It is the most effective challenge type, but it is also the most resource intensive and slowest to load.
116 |
117 | `managed_challenge` is the default challenge type. Cloudflare will choose to use `js_challenge` or `challenge` based on how likely it thinks the request is a bot.
118 |
119 | Usually it is best to start with `managed_challenge` and then switch to `challenge` if the bots are still able to bypass the challenge.
120 |
121 | If you change this after the inital setup, you will need to remove the rule from the dashboard and run the script again.
122 |
123 | ### 8. Discord Webhook (optional)
124 | `If you want to use a Discord webhook, please enter the webhook URL (default: None)`
125 |
126 | This is the Discord webhook URL you want to use. You can find a guide [here](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks). It should be a valid Discord webhook URL. You will get messages when the challenge is enabled or disabled.
127 |
128 | If you don't want to use a Discord webhook, you can leave it blank.
129 |
130 | ### 9. Telegram Bot Token (optional)
131 | `If you want to use a Telegram bot, please enter the bot token (default: None)`
132 |
133 | This is the Telegram bot token you want to use. You can find a guide [here](https://core.telegram.org/bots/tutorial#obtain-your-bot-token). It should be a valid Telegram bot token. You will get messages when the challenge is enabled or disabled. If you set a bot token, you will also need to set a chat ID.
134 |
135 | If you don't want to get Telegram notifications, you can leave it blank.
136 |
137 | ### 9.1. Telegram Chat ID (optional, only if you set a Telegram bot token)
138 | `Please enter the chat ID for the telegram bot (default: None)`
139 |
140 | This is the chat ID you want to use. You can find a guide [here](https://core.telegram.org/bots/tutorial#obtain-your-chat-id). It should be a valid Telegram chat ID. You will get messages when the challenge is enabled or disabled. If you set a bot token, you will also need to set a chat ID.
141 |
142 | If you haven't set a bot token, you will not see this prompt.
143 |
144 | ### 10. Challenge Rule Disable Delay
145 | `How many seconds do you want to wait before disabling the challenge rule? (default: 30)`
146 |
147 | This is the delay in seconds you want to use before disabling the challenge rule. This is to avoid the rule to be disabled and enabled fast when the CPU lowers because of the challenge. It should be a number between 0 and infinity. But it is advised to set it to a value between 5 and 1800.
148 |
149 |
150 | ## Usage
151 |
152 | After installation, run:
153 |
154 | ```bash
155 | cf-shield
156 | ```
157 |
158 | Or if you want to use it as a Python module:
159 |
160 | ```python
161 | from cf_shield import run
162 | run()
163 | ```
164 |
165 | To modify the config, you can edit the .env file.
166 |
167 | ## Roadmap
168 | - [x] Adding a way to add multiple domains.
169 | - [x] Making the challenge type customizable instead of `managed_challenge`.
170 | - [x] Discord webhook notifications.
171 | - [x] Adding a configurable delay before disabling the challenge rule.
172 | - [x] Telegram notifications.
173 | - [x] Full guide in the README.md.
174 | - [x] A way to use all domains in the zone.
175 | - [ ] Slack notifications.
176 | - [ ] Add ratelimit challenge.
177 |
178 |
179 | ## Contributing
180 |
181 | Pull requests are welcome. For major changes, please open an issue first
182 | to discuss what you would like to change.
183 |
184 | Please make sure to update tests as appropriate.
185 |
186 | ## License
187 |
188 | [GPL-3.0](https://choosealicense.com/licenses/gpl-3.0/)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CF-Shield
2 |
3 | CF-Shield is a Python script for detecting DDoS attacks and enabling security measures on Cloudflare automatically.
4 |
5 | ## Installation
6 |
7 | ### Way 1: Using pip
8 |
9 | ```bash
10 | pip install cf-shield
11 | ```
12 |
13 | Then to run the script, you can use the following command:
14 |
15 | ```bash
16 | cf-shield
17 | ```
18 | or if it is not in your PATH, you can use the following command:
19 |
20 | ```bash
21 | python3 -m cf-shield
22 | ```
23 |
24 | If this fails, you can try using git.
25 |
26 |
27 | ### Way 2: Using git
28 |
29 | First, you will need to get your Cloudflare email, API token, zone ID, and account ID.
30 |
31 | ```bash
32 | git clone https://github.com/Sakura-sx/cf-shield.git
33 | cd cf-shield
34 | python3 main.py
35 | ```
36 | When running the script for the first time, it will ask you for your Cloudflare email, API token, zone ID, and account ID. More info on [Setup](#setup).
37 |
38 | The dependencies should be installed automatically. If not, you can install them manually by running `python3 -m pip install -r requirements.txt`.
39 |
40 | ## Setup
41 | To setup the script, you will need to run the script and follow the prompts. First run the commands on [Installation](#installation). Here you have a list of what the script will ask you for and what you need to do. The prompts with `default:` are optional and will be set to the default value if you don't enter anything.
42 |
43 | Here is an example of the setup, in diff format for better readability:
44 | ```diff
45 | +the parts in green are the prompts that you will see
46 | -the parts in red are an example of what a user would enter
47 | ```
48 | Please ignore the `+` and `-` signs, they are only for formatting. They are not part of the setup. You should not enter them.
49 |
50 | ```diff
51 | /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$
52 | /$$__ $$| $$_____/ /$$__ $$| $$ |__/ | $$ | $$
53 | | $$ \__/| $$ | $$ \__/| $$$$$$$ /$$ /$$$$$$ | $$ /$$$$$$$
54 | | $$ | $$$$$ /$$$$$$| $$$$$$ | $$__ $$| $$ /$$__ $$| $$ /$$__ $$
55 | | $$ | $$__/|______/ \____ $$| $$ \ $$| $$| $$$$$$$$| $$| $$ | $$
56 | | $$ $$| $$ /$$ \ $$| $$ | $$| $$| $$_____/| $$| $$ | $$
57 | | $$$$$$/| $$ | $$$$$$/| $$ | $$| $$| $$$$$$$| $$| $$$$$$$
58 | \______/ |__/ \______/ |__/ |__/|__/ \_______/|__/ \_______/
59 |
60 |
61 |
62 |
63 | +Welcome to CF-Shield, we will now set it up for you.
64 | +What's the domain(s) you want to use? (e.g. "example.com,www.example.com" or "example.com")
65 | -example.com
66 | +What's the email you used to sign up for Cloudflare? (e.g. example@example.com)
67 | -example@example.com
68 | +Please create an API token and copy it here (e.g. aK-MaF3oyTrPDD8YoNBlvqo0ous7BOeSA7te84OR)
69 | -aK-MaF3oyTrPDD8YoNBlvqo0ous7BOeSA7te84OR
70 | +Please copy the zone ID from the URL of your Cloudflare dashboard (e.g. 1b7c0e3d41f09ceb9cbcde6b0c7bc819)
71 | -1b7c0e3d41f09ceb9cbcde6b0c7bc819
72 | +Please copy the account ID from the URL of your Cloudflare dashboard (e.g. 6dead821d9eb4c42f8a8dda399651660)
73 | -6dead821d9eb4c42f8a8dda399651660
74 | +Please enter the CPU usage threshold in percentage (default: 80)
75 | -80
76 | +What's the challenge type you want to use? (default: managed_challenge, options: managed_challenge, js_challenge, challenge)
77 | -managed_challenge
78 | +If you want to use a Discord webhook, please enter the webhook URL (default: None)
79 | -https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz
80 | +If you want to use a custom message, please enter the message (default: The CPU usage is too high, enabling challenge rule for example.com...)
81 | -The CPU usage is too high, enabling challenge rule for example.com...
82 | +If you want to use a Slack webhook, please enter the webhook URL (default: None)
83 | -https://hooks.slack.com/services/1234567890/abcdefghijklmnopqrstuvwxyz
84 | +If you want to use a custom message, please enter the message (default: The CPU usage is too high, enabling challenge rule for example.com...)
85 | -The CPU usage is too high, enabling challenge rule for example.com...
86 | +If you want to use a Telegram bot, please enter the bot token (default: None)
87 | -1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ
88 | +Please enter the chat ID for the telegram bot (default: None)
89 | -1234567890
90 | +If you want to use a custom message, please enter the message (default: The CPU usage is too high, enabling challenge rule for example.com...)
91 | -The CPU usage is too high, enabling challenge rule for example.com...
92 | +How many seconds do you want to wait before disabling the challenge rule? (default: auto eg. 30)
93 | -30
94 | +Please enter the range of the averaged CPU monitoring (default: 10)
95 | -10
96 | +Setup successful!
97 | + Ruleset ID: abacebd975b04e398fe02ba19614aa8b
98 | + Rule ID: e65dd32a32874c0aa3339af385ca95db
99 | +Saving configuration to .env file...
100 | +Configuration saved successfully!
101 | +Setup complete! Starting monitoring...
102 | ```
103 |
104 | ### 1. Domains
105 | `What's the domain(s) you want to use? (default: all, e.g. "example.com,www.example.com" or "example.com")`
106 |
107 | This is the domain(s) you want to use. You can add multiple domains by separating them with a comma. The domains must be on the same [Zone](https://developers.cloudflare.com/fundamentals/concepts/accounts-and-zones/#zones) (meaning a single WAF rule can be applied to all of them).
108 |
109 | If you want to use all domains in the zone, you can enter `all`.
110 |
111 | If you change this after the inital setup, you will need to remove the rule from the dashboard and run the script again.
112 |
113 | ### 2. Email
114 | `What's the email you used to sign up for Cloudflare? (e.g. example@example.com)`
115 |
116 | This must be the email you used to sign up for Cloudflare. You can find it [here](https://dash.cloudflare.com/profile).
117 |
118 | ### 3. API Token
119 | `Please create an API token and copy it here (e.g. aK-MaF3oyTrPDD8YoNBlvqo0ous7BOeSA7te84OR)`
120 |
121 | This is the API token you need to create. You can create it [here](https://dash.cloudflare.com/profile/api-tokens). There is a guide [here](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/). You need to create a token with `Zone WAF Write` permissions. It should be 40 characters long and only contain letters, numbers and dashes.
122 |
123 | ### 4. Zone ID
124 | `Please copy the zone ID from the URL of your Cloudflare dashboard (e.g. 1b7c0e3d41f09ceb9cbcde6b0c7bc819)`
125 |
126 | This is the zone ID you need to copy from the URL of your Cloudflare dashboard. You can find it [here](https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/#copy-your-zone-id). It should be 32 characters long and only contain letters and numbers.
127 |
128 | ### 5. Account ID
129 | `Please copy the account ID from the URL of your Cloudflare dashboard (e.g. 6dead821d9eb4c42f8a8dda399651660)`
130 |
131 | The account ID can be found below the zone ID. It should not be the same as the zone ID. If you can't find it, there is more info [here](https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/#copy-your-account-id). It should be 32 characters long and only contain letters and numbers.
132 |
133 | #### This was the last prompt you could not set blank. After setting this you can leave blank the other prompts.
134 |
135 | ### 6. CPU Threshold
136 | `Please enter the CPU usage threshold in percentage (default: 80)`
137 |
138 | This is the CPU usage threshold you want to use. The script will enable the challenge rule if the CPU usage is greater than this threshold. It should be a number between 0 and 100. It is advised to set it to a value between 50 and 90 depending on your server's performance and average load.
139 |
140 | ### 7. Challenge Type
141 | `What's the challenge type you want to use? (default: managed_challenge, options: managed_challenge, js_challenge, challenge)`
142 |
143 | This is the challenge type you want to use. You can choose between `managed_challenge`, `js_challenge` and `challenge`.
144 |
145 | `js_challenge` is a challenge that uses JavaScript to detect bots. It is the fastest challenge type to load, but it is also not as effective as `challenge` or `managed_challenge`.
146 |
147 | `challenge` is a challenge that uses a CAPTCHA to detect bots, it was the first challenge type to be released by Cloudflare. It is the most effective challenge type, but it is also the most resource intensive and slowest to load.
148 |
149 | `managed_challenge` is the default challenge type. Cloudflare will choose to use `js_challenge` or `challenge` based on how likely it thinks the request is a bot.
150 |
151 | Usually it is best to start with `managed_challenge` and then switch to `challenge` if the bots are still able to bypass the challenge.
152 |
153 | If you change this after the inital setup, you will need to remove the rule from the dashboard and run the script again.
154 |
155 | ### 8. Discord Webhook (optional)
156 | `If you want to use a Discord webhook, please enter the webhook URL (default: None)`
157 |
158 | This is the Discord webhook URL you want to use. You can find a guide [here](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks). It should be a valid Discord webhook URL. You will get messages when the challenge is enabled or disabled.
159 |
160 | If you don't want to use a Discord webhook, you can leave it blank.
161 |
162 | ### 8.1. Discord Custom Message (optional, only if you set a Discord webhook)
163 | `If you want to use a custom message for the attack start, please enter the message (default: The CPU usage is too high, enabling challenge rule for example.com...)`
164 |
165 | This is the custom message you want to use when the CPU usage is too high.
166 |
167 | If you don't want to use a custom message, you can leave it blank.
168 |
169 | ### 8.2. Discord Custom Message Attack End (optional, only if you set a Discord webhook)
170 | `If you want to use a custom message for the attack end, please enter the message (default: The CPU usage is back to normal, disabling challenge rule for example.com...)`
171 |
172 | This is the custom message you want to use when the CPU usage is back to normal.
173 |
174 | If you don't want to use a custom message, you can leave it blank.
175 |
176 | ### 8.3. Discord Custom Message 10 Seconds After Attack Started (optional, only if you set a Discord webhook)
177 | `If you want to use a custom message, please enter the message (default: The CPU usage is still too high, the challenge rule might not be working...)`
178 |
179 | This is the custom message you want to use when the CPU usage is still too high 10 seconds after the attack started.
180 |
181 | If you don't want to use a custom message, you can leave it blank.
182 |
183 | ### 9. Telegram Bot Token (optional)
184 | `If you want to use a Telegram bot, please enter the bot token (default: None)`
185 |
186 | This is the Telegram bot token you want to use. You can find a guide [here](https://core.telegram.org/bots/tutorial#obtain-your-bot-token). It should be a valid Telegram bot token. You will get messages when the challenge is enabled or disabled. If you set a bot token, you will also need to set a chat ID.
187 |
188 | If you don't want to get Telegram notifications, you can leave it blank.
189 |
190 | ### 9.1. Telegram Chat ID (optional, only if you set a Telegram bot token)
191 | `Please enter the chat ID for the telegram bot (default: None)`
192 |
193 | This is the chat ID you want to use. You can find a guide [here](https://core.telegram.org/bots/tutorial#obtain-your-chat-id). It should be a valid Telegram chat ID. You will get messages when the challenge is enabled or disabled. If you set a bot token, you will also need to set a chat ID.
194 |
195 | If you haven't set a bot token, you will not see this prompt.
196 |
197 | ### 9.2. Telegram Custom Message Attack Start (optional, only if you set a Telegram bot token)
198 | `If you want to use a custom message for the attack start, please enter the message (default: The CPU usage is too high, enabling challenge rule for example.com...)`
199 |
200 | This is the custom message you want to use when the CPU usage is too high.
201 |
202 | If you don't want to use a custom message, you can leave it blank.
203 |
204 | ### 9.3. Telegram Custom Message Attack End (optional, only if you set a Telegram bot token)
205 | `If you want to use a custom message for the attack end, please enter the message (default: The CPU usage is back to normal, disabling challenge rule for example.com...)`
206 |
207 | This is the custom message you want to use when the CPU usage is back to normal.
208 |
209 | If you don't want to use a custom message, you can leave it blank.
210 |
211 | ### 9.4. Telegram Custom Message 10 Seconds After Attack Started (optional, only if you set a Telegram bot token)
212 | `If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: The CPU usage is still too high, the challenge rule might not be working...)`
213 |
214 | This is the custom message you want to use when the CPU usage is still too high 10 seconds after the attack started.
215 |
216 | If you don't want to use a custom message, you can leave it blank.
217 |
218 | ### 10. Slack Webhook (optional)
219 | `If you want to use a Slack webhook, please enter the webhook URL (default: None)`
220 |
221 | This is the Slack webhook URL you want to use. You can find a guide [here](https://api.slack.com/messaging/webhooks). It should be a valid Slack webhook URL. You will get messages when the challenge is enabled or disabled.
222 |
223 | If you don't want to use a Slack webhook, you can leave it blank.
224 |
225 | ### 10.1. Slack Custom Message (optional, only if you set a Slack webhook)
226 | `If you want to use a custom message for the attack start, please enter the message (default: The CPU usage is too high, enabling challenge rule for example.com...)`
227 |
228 | This is the custom message you want to use when the CPU usage is too high.
229 |
230 | If you don't want to use a custom message, you can leave it blank.
231 |
232 | ### 10.2. Slack Custom Message Attack End (optional, only if you set a Slack webhook)
233 | `If you want to use a custom message for the attack end, please enter the message (default: The CPU usage is back to normal, disabling challenge rule for example.com...)`
234 |
235 | This is the custom message you want to use when the CPU usage is back to normal.
236 |
237 | If you don't want to use a custom message, you can leave it blank.
238 |
239 | ### 10.3. Slack Custom Message 10 Seconds After Attack Started (optional, only if you set a Slack webhook)
240 | `If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: The CPU usage is still too high, the challenge rule might not be working...)`
241 |
242 | This is the custom message you want to use when the CPU usage is still too high 10 seconds after the attack started.
243 |
244 | If you don't want to use a custom message, you can leave it blank.
245 |
246 | ### 11. Challenge Rule Disable Delay
247 | `How many seconds do you want to wait before disabling the challenge rule? (default: auto eg. 30)`
248 |
249 | This is the delay in seconds you want to use before disabling the challenge rule. This is to avoid the rule to be disabled and enabled fast when the CPU lowers because of the challenge. It should be a number between 0 and infinity. But it is advised to set it to a value between 5 and 1800. You can also set it to "auto" and the script will choose the value dynamically.
250 |
251 | ### 12. Averaged CPU Monitoring
252 | `Do you want to use averaged CPU monitoring? (default: yes)`
253 |
254 | Setting this to "yes" uses the last 10 values of the CPU to calculate the average CPU usage. This is to avoid the script to detect a CPU spike when there is no attack.
255 |
256 | On the next setting you can configure the range of the averaged CPU monitoring to be something else than 10.
257 |
258 | ### 13. Average CPU Monitoring range (optional, only if you set averaged CPU monitoring to "yes")
259 | `Please enter the range of the averaged CPU monitoring (default: 10)`
260 |
261 | This is the range of the averaged CPU monitoring. It should be a number between 2 and 120. It is advised to set it to a value between 5 and 30.
262 |
263 | ## Usage
264 | ```bash
265 | cf-shield
266 | ```
267 | or if it is not in your PATH, you can use the following command:
268 | ```bash
269 | python3 -m cf-shield
270 | ```
271 |
272 | Or if it doesn't work, you can install it using git. (See [Installation](#installation)) and then run the following command:
273 |
274 | ```bash
275 | python3 main.py
276 | ```
277 | To modify the config after the inital setup, you can edit the .env file or use the `setup` argument like this (See [Setup](#setup)):
278 |
279 | ```bash
280 | python3 main.py setup
281 | ```
282 |
283 |
284 |
285 |
286 | ## Roadmap
287 | - [x] Adding a way to add multiple domains.
288 | - [x] Making the challenge type customizable instead of `managed_challenge`.
289 | - [x] Discord webhook notifications.
290 | - [x] Adding a configurable delay before disabling the challenge rule.
291 | - [x] Telegram notifications.
292 | - [x] Full guide in the README.md.
293 | - [x] A way to use all domains in the zone.
294 | - [x] Slack notifications.
295 | - [x] Set disable delay automatically.
296 | - [x] Averaged CPU monitoring option.
297 | - [x] Customizable alert messages.
298 | - [x] Send an alert when the challenge rule does not make the CPU usage go down.
299 | - [x] Trigger based on network traffic.
300 | - [ ] Placeholders on the custom alert messages.
301 | - [ ] Add ntfy.sh notifications.
302 | - [ ] Automated CPU spike detection option.
303 | - [ ] Add ratelimit challenge.
304 |
305 |
306 | ## Contributing
307 |
308 | Pull requests are welcome. For major changes, please open an issue first
309 | to discuss what you would like to change.
310 |
311 | ## License
312 |
313 | [GPL-3.0](https://choosealicense.com/licenses/gpl-3.0/)
--------------------------------------------------------------------------------
/python-package/src/cf_shield/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import sys
4 | import requests
5 | import psutil
6 | from cloudflare import Cloudflare
7 | from dotenv import load_dotenv
8 | from discord_webhook import DiscordWebhook
9 | import time
10 | import logging
11 | import colorlog
12 | from colorlog import ColoredFormatter
13 | from slack_sdk.webhook import WebhookClient
14 |
15 | def setup():
16 | print("What's the domain(s) you want to use? (default: all, e.g. \"example.com,www.example.com\" or \"example.com\")")
17 | domains = input().strip().split(",")
18 | if not domains:
19 | domains = ["all"]
20 | else:
21 | if domains[0] != "all":
22 | for domain in domains:
23 | if domain.strip() == "":
24 | logging.error("No domain provided, please provide a domain")
25 | return
26 | elif not re.match(r"^((?!-)[A-Za-z0-9-]{1,63}(? 100:
78 | logging.error("CPU threshold cannot be greater than 100")
79 | return
80 | elif int(cpu_threshold) < 10:
81 | logging.error("You have set the CPU threshold to a very low value, if you know what you are doing, you can ignore this message")
82 | elif int(cpu_threshold) <= 0:
83 | logging.error("CPU threshold cannot be less than or equal to 0")
84 | return
85 | print("What's the challenge type you want to use? (default: managed_challenge, options: managed_challenge, js_challenge, challenge)")
86 | challenge_type = input().strip()
87 | if not challenge_type:
88 | challenge_type = "managed_challenge"
89 | elif challenge_type not in ["managed_challenge", "js_challenge", "challenge"]:
90 | logging.error("Invalid challenge type, please enter a valid challenge type")
91 | return
92 | logging.debug(f"Challenge type: {challenge_type}")
93 |
94 |
95 | print("If you want to use a Slack webhook, please enter the webhook URL (default: None)")
96 | slack_webhook = input().strip()
97 | if not slack_webhook:
98 | slack_webhook = None
99 | else:
100 | if not re.match(r"^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9\/]+$", slack_webhook):
101 | logging.error("Invalid Slack webhook URL, please enter a valid Slack webhook URL")
102 | return
103 | else:
104 | logging.info("Sending a test message to the Slack webhook...")
105 | try:
106 | webhook = WebhookClient(slack_webhook)
107 | webhook.send(text="Test message from CF-Shield")
108 | logging.info("Test message sent successfully!")
109 | except Exception as e:
110 | logging.error(f"Error sending test message to Slack webhook: {e}")
111 | return
112 | else:
113 | print("If you want to use a custom message for the attack start, please enter the message (default: The CPU usage is too high, enabling challenge rule for {', '.join(domains)}...)")
114 | slack_custom_message = input().strip()
115 | if not slack_custom_message:
116 | slack_custom_message = f"The CPU usage is too high, enabling challenge rule for {', '.join(domains)}..."
117 |
118 | print(f"If you want to use a custom message for the attack end, please enter the message (default: The CPU usage is back to normal, disabling challenge rule for {', '.join(domains)}...)")
119 | slack_custom_message_end = input().strip()
120 | if not slack_custom_message_end:
121 | slack_custom_message_end = f"The CPU usage is back to normal, disabling challenge rule for {', '.join(domains)}..."
122 |
123 | print("If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: The CPU usage is still too high, disabling challenge rule for {', '.join(domains)}...)")
124 | slack_custom_message_10_seconds = input().strip()
125 | if not slack_custom_message_10_seconds:
126 | slack_custom_message_10_seconds = f"The CPU usage is still too high, the challenge rule might not be working..."
127 |
128 | logging.debug(f"Slack webhook: {slack_webhook}")
129 | logging.debug(f"Slack custom message: {slack_custom_message}")
130 | logging.debug(f"Slack custom message end: {slack_custom_message_end}")
131 | logging.debug(f"Slack custom message 10 seconds: {slack_custom_message_10_seconds}")
132 |
133 |
134 | print("If you want to use a Discord webhook, please enter the webhook URL (default: None)")
135 | discord_webhook = input().strip()
136 | if not discord_webhook:
137 | discord_webhook = None
138 | else:
139 | if not re.match(r"^https:\/\/(discord\.com|ptb\.discord\.com|canary\.discord\.com)\/api\/webhooks\/[0-9]+\/[a-zA-Z0-9-]+$", discord_webhook):
140 | logging.error("Invalid Discord webhook URL, please enter a valid Discord webhook URL")
141 | return
142 | else:
143 | logging.info("Sending a test message to the Discord webhook...")
144 | try:
145 | webhook = DiscordWebhook(url=discord_webhook, content="Test message from CF-Shield")
146 | webhook.execute()
147 | logging.info("Test message sent successfully!")
148 | except Exception as e:
149 | logging.error(f"Error sending test message to Discord webhook: {e}")
150 | return
151 | else:
152 | print(f"If you want to use a custom message for the attack start, please enter the message (default: The CPU usage is too high, enabling challenge rule for {', '.join(domains)}...)")
153 | discord_custom_message = input().strip()
154 | if not discord_custom_message:
155 | discord_custom_message = f"The CPU usage is too high, enabling challenge rule for {', '.join(domains)}..."
156 |
157 | print(f"If you want to use a custom message for the attack end, please enter the message (default: The CPU usage is back to normal, disabling challenge rule for {', '.join(domains)}...)")
158 | discord_custom_message_end = input().strip()
159 | if not discord_custom_message_end:
160 | discord_custom_message_end = f"The CPU usage is back to normal, disabling challenge rule for {', '.join(domains)}..."
161 |
162 | print("If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: The CPU usage is still too high, the challenge rule might not be working...)")
163 | discord_custom_message_10_seconds = input().strip()
164 | if not discord_custom_message_10_seconds:
165 | discord_custom_message_10_seconds = f"The CPU usage is still too high, the challenge rule might not be working..."
166 |
167 | logging.debug(f"Discord webhook: {discord_webhook}")
168 | logging.debug(f"Discord custom message: {discord_custom_message}")
169 | logging.debug(f"Discord custom message end: {discord_custom_message_end}")
170 | logging.debug(f"Discord custom message 10 seconds: {discord_custom_message_10_seconds}")
171 |
172 |
173 | print("If you want to use a Telegram bot, please enter the bot token (default: None)")
174 | telegram_bot_token = input().strip()
175 | if not telegram_bot_token:
176 | telegram_bot_token = None
177 | else:
178 | if not re.match(r"([0-9]{8,10}):[A-za-z0-9]{35}", telegram_bot_token):
179 | logging.error("Invalid Telegram bot token, please enter a valid Telegram bot token")
180 | return
181 | print("Please enter the chat ID for the telegram bot")
182 | telegram_chat_id = input().strip()
183 | if not re.match(r"^[0-9]+$", telegram_chat_id):
184 | logging.error("Invalid Telegram chat ID, please enter a valid Telegram chat ID")
185 | return
186 | else:
187 | logging.info("Sending a test message to the Telegram bot...")
188 | try:
189 | send_telegram_message("Test message from CF-Shield", telegram_chat_id, telegram_bot_token)
190 | logging.info("Test message sent successfully!")
191 | except Exception as e:
192 | logging.error(f"Error sending test message to Telegram bot: {e}")
193 | else:
194 | print(f"If you want to use a custom message for the attack start, please enter the message (default: The CPU usage is too high, enabling challenge rule for {', '.join(domains)}...)")
195 | telegram_custom_message = input().strip()
196 | if not telegram_custom_message:
197 | telegram_custom_message = f"The CPU usage is too high, enabling challenge rule for {', '.join(domains)}..."
198 |
199 | print(f"If you want to use a custom message for the attack end, please enter the message (default: The CPU usage is back to normal, disabling challenge rule for {', '.join(domains)}...)")
200 | telegram_custom_message_end = input().strip()
201 | if not telegram_custom_message_end:
202 | telegram_custom_message_end = f"The CPU usage is back to normal, disabling challenge rule for {', '.join(domains)}..."
203 | print("If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: The CPU usage is still too high, the challenge rule might not be working...)")
204 |
205 | telegram_custom_message_10_seconds = input().strip()
206 | if not telegram_custom_message_10_seconds:
207 | telegram_custom_message_10_seconds = f"The CPU usage is still too high, the challenge rule might not be working..."
208 |
209 | logging.debug(f"Telegram bot token: {telegram_bot_token}")
210 | logging.debug(f"Telegram chat ID: {telegram_chat_id}")
211 | logging.debug(f"Telegram custom message: {telegram_custom_message}")
212 | logging.debug(f"Telegram custom message end: {telegram_custom_message_end}")
213 | logging.debug(f"Telegram custom message 10 seconds: {telegram_custom_message_10_seconds}")
214 |
215 |
216 | print("How many seconds do you want to wait before disabling the challenge rule? (default: auto eg. 30)")
217 | disable_delay = input().strip()
218 | if not disable_delay:
219 | disable_delay = "auto"
220 | elif not re.match(r"^[0-9]+$", disable_delay):
221 | logging.error("Invalid disable delay, please enter a valid disable delay")
222 | return
223 | elif disable_delay < 0:
224 | logging.error("Disable delay cannot be less than 0")
225 | return
226 | elif disable_delay < 5:
227 | logging.warning("You have set the disable delay to a very low value, if you know what you are doing, you can ignore this message")
228 | elif disable_delay > 1800:
229 | logging.warning("You have set the disable delay to a very high value, if you know what you are doing, you can ignore this message")
230 | logging.debug(f"Disable delay: {disable_delay}")
231 |
232 |
233 | print("Do you want to use averaged CPU monitoring? (default: yes)")
234 | averaged_cpu_monitoring = input().strip().lower()
235 | if not averaged_cpu_monitoring:
236 | averaged_cpu_monitoring = True
237 | elif averaged_cpu_monitoring in ["true", "yes", "y"]:
238 | averaged_cpu_monitoring = True
239 | elif averaged_cpu_monitoring in ["false", "no", "n"]:
240 | averaged_cpu_monitoring = False
241 | else:
242 | logging.error("Invalid averaged CPU monitoring, setting to default (yes)")
243 | averaged_cpu_monitoring = True
244 | logging.debug(f"Averaged CPU monitoring: {averaged_cpu_monitoring}")
245 |
246 |
247 | print("Please enter the range of the averaged CPU monitoring (default: 10)")
248 | averaged_cpu_monitoring_range = input().strip()
249 | if not averaged_cpu_monitoring_range:
250 | averaged_cpu_monitoring_range = 10
251 | elif not re.match(r"^[0-9]+$", averaged_cpu_monitoring_range):
252 | logging.error("Invalid averaged CPU monitoring range, please enter a valid averaged CPU monitoring range")
253 | return
254 | elif int(averaged_cpu_monitoring_range) < 2:
255 | logging.error("Averaged CPU monitoring range cannot be less than 2")
256 | return
257 | elif int(averaged_cpu_monitoring_range) > 120:
258 | logging.warning("Averaged CPU monitoring range is too high, you can ignore this message if you know what you are doing")
259 | logging.debug(f"Averaged CPU monitoring range: {averaged_cpu_monitoring_range}")
260 |
261 |
262 | cf = Cloudflare(api_token=api_token)
263 |
264 | try:
265 | rulesets_page = cf.rulesets.list(zone_id=zone_id)
266 | logging.debug(f"Rulesets: {rulesets_page}")
267 |
268 | target_ruleset_id = None
269 | for ruleset in rulesets_page.result:
270 | if ruleset.phase == "http_request_firewall_custom":
271 | target_ruleset_id = ruleset.id
272 | break
273 | logging.debug(f"Target ruleset ID: {target_ruleset_id}")
274 |
275 | if not target_ruleset_id:
276 | logging.info("No http_request_firewall_custom ruleset found.")
277 |
278 | custom_ruleset = cf.rulesets.create(
279 | kind="zone",
280 | name="cf-shield-challenge",
281 | phase="http_request_firewall_custom",
282 | zone_id=zone_id
283 | )
284 | target_ruleset_id = custom_ruleset.id
285 | logging.debug(f"Target ruleset ID: {target_ruleset_id}")
286 |
287 | existing_ruleset = cf.rulesets.get(zone_id=zone_id, ruleset_id=target_ruleset_id)
288 | logging.debug(f"Existing ruleset: {existing_ruleset}")
289 |
290 | cf_shield_rule_id = None
291 | try:
292 | for rule in existing_ruleset.rules:
293 | if rule.description and "CF-Shield" in rule.description:
294 | cf_shield_rule_id = rule.id
295 | break
296 | except Exception as e:
297 | logging.error(f"Error checking for existing CF-Shield rule: {e}")
298 | cf_shield_rule_id = None
299 | logging.debug(f"CF-Shield rule ID: {cf_shield_rule_id}")
300 |
301 | if not cf_shield_rule_id:
302 | expression = "("
303 | if domains[0] != "all":
304 | for domain in domains:
305 | expression += f"http.host eq \"{domain}\" or "
306 | expression = expression[:-4] + ")"
307 | else:
308 | expression = "(http.host ne \"example.invalid\")"
309 | new_rule = cf.rulesets.rules.create(
310 | ruleset_id=target_ruleset_id,
311 | zone_id=zone_id,
312 | action=challenge_type,
313 | expression=expression,
314 | description="CF-Shield",
315 | enabled=False
316 | )
317 | cf_shield_rule_id = new_rule.id
318 | logging.debug(f"CF-Shield rule ID: {cf_shield_rule_id}")
319 |
320 | print(f"Setup successful!")
321 | print(f" Ruleset ID: {target_ruleset_id}")
322 | print(f" Rule ID: {cf_shield_rule_id}")
323 |
324 | except Exception as e:
325 | logging.error(f"Error working with rulesets: {e}")
326 | logging.error("Note: You may need to adjust your API token permissions.")
327 | return
328 |
329 | print("Saving configuration to .env file...")
330 | try:
331 | with open(".env", "w") as f:
332 | f.write(f"CF_EMAIL={email}\n")
333 | f.write(f"CF_API_TOKEN={api_token}\n")
334 | f.write(f"CF_ZONE_ID={zone_id}\n")
335 | f.write(f"CF_ACCOUNT_ID={account_id}\n")
336 | f.write(f"CF_RULESET_ID={target_ruleset_id}\n")
337 | f.write(f"CF_RULE_ID={cf_shield_rule_id}\n")
338 | f.write(f"DOMAINS={','.join(domains)}\n")
339 | f.write(f"CPU_THRESHOLD={cpu_threshold}\n")
340 | f.write(f"CHALLENGE_TYPE={challenge_type}\n")
341 | f.write(f"SLACK_WEBHOOK={slack_webhook}\n")
342 | f.write(f"SLACK_CUSTOM_MESSAGE={slack_custom_message}\n")
343 | f.write(f"SLACK_CUSTOM_MESSAGE_END={slack_custom_message_end}\n")
344 | f.write(f"SLACK_CUSTOM_MESSAGE_10_SECONDS={slack_custom_message_10_seconds}\n")
345 | f.write(f"DISCORD_WEBHOOK={discord_webhook}\n")
346 | f.write(f"DISCORD_CUSTOM_MESSAGE={discord_custom_message}\n")
347 | f.write(f"DISCORD_CUSTOM_MESSAGE_END={discord_custom_message_end}\n")
348 | f.write(f"DISCORD_CUSTOM_MESSAGE_10_SECONDS={discord_custom_message_10_seconds}\n")
349 | f.write(f"TELEGRAM_BOT_TOKEN={telegram_bot_token}\n")
350 | f.write(f"TELEGRAM_CHAT_ID={telegram_chat_id}\n")
351 | f.write(f"TELEGRAM_CUSTOM_MESSAGE={telegram_custom_message}\n")
352 | f.write(f"TELEGRAM_CUSTOM_MESSAGE_END={telegram_custom_message_end}\n")
353 | f.write(f"TELEGRAM_CUSTOM_MESSAGE_10_SECONDS={telegram_custom_message_10_seconds}\n")
354 | f.write(f"DISABLE_DELAY={disable_delay}\n")
355 | f.write(f"AVERAGED_CPU_MONITORING={averaged_cpu_monitoring}\n")
356 | f.write(f"AVERAGED_CPU_MONITORING_RANGE={averaged_cpu_monitoring_range}\n")
357 | f.write(f"SETUP=true\n")
358 | print("Configuration saved successfully!")
359 | except Exception as e:
360 | logging.error(f"Error saving configuration: {e}")
361 | return
362 |
363 | print("Setup complete! Starting monitoring...")
364 | main()
365 |
366 | def send_telegram_message(message, chat_id, bot_token):
367 | url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
368 | data = {
369 | "chat_id": chat_id,
370 | "text": message
371 | }
372 | requests.post(url, json=data)
373 |
374 | def main():
375 |
376 | cf = Cloudflare(api_token=os.getenv("CF_API_TOKEN"))
377 | zone_id = os.getenv("CF_ZONE_ID")
378 | account_id = os.getenv("CF_ACCOUNT_ID")
379 | ruleset_id = os.getenv("CF_RULESET_ID")
380 | rule_id = os.getenv("CF_RULE_ID")
381 | domains = os.getenv("DOMAINS").split(",") if "," in os.getenv("DOMAINS") else [os.getenv("DOMAINS")]
382 | cpu_threshold = int(os.getenv("CPU_THRESHOLD", 80))
383 | challenge_type = os.getenv("CHALLENGE_TYPE", "managed_challenge")
384 | slack_webhook = os.getenv("SLACK_WEBHOOK", None)
385 | slack_custom_message = os.getenv("SLACK_CUSTOM_MESSAGE", None)
386 | slack_custom_message_end = os.getenv("SLACK_CUSTOM_MESSAGE_END", None)
387 | slack_custom_message_10_seconds = os.getenv("SLACK_CUSTOM_MESSAGE_10_SECONDS", None)
388 | discord_webhook = os.getenv("DISCORD_WEBHOOK", None)
389 | discord_custom_message = os.getenv("DISCORD_CUSTOM_MESSAGE", None)
390 | discord_custom_message_end = os.getenv("DISCORD_CUSTOM_MESSAGE_END", None)
391 | discord_custom_message_10_seconds = os.getenv("DISCORD_CUSTOM_MESSAGE_10_SECONDS", None)
392 | telegram_bot_token = os.getenv("TELEGRAM_BOT_TOKEN", None)
393 | telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID", None)
394 | telegram_custom_message = os.getenv("TELEGRAM_CUSTOM_MESSAGE", None)
395 | telegram_custom_message_end = os.getenv("TELEGRAM_CUSTOM_MESSAGE_END", None)
396 | telegram_custom_message_10_seconds = os.getenv("TELEGRAM_CUSTOM_MESSAGE_10_SECONDS", None)
397 | disable_delay = os.getenv("DISABLE_DELAY", "auto")
398 | averaged_cpu_monitoring = os.getenv("AVERAGED_CPU_MONITORING", True)
399 | averaged_cpu_monitoring_range = os.getenv("AVERAGED_CPU_MONITORING_RANGE", 10)
400 |
401 | if not all([zone_id, ruleset_id, rule_id]):
402 | logging.error("Missing configuration. Please run setup again.")
403 | logging.error(f"Zone ID: {zone_id}")
404 | logging.error(f"Ruleset ID: {ruleset_id}")
405 | logging.error(f"Rule ID: {rule_id}")
406 | return
407 |
408 | logging.info(f"Monitoring CPU usage for domains: {', '.join(domains)}")
409 | logging.info(f"CPU threshold: {cpu_threshold}%")
410 |
411 | rule_enabled = False
412 | t = 1
413 | if disable_delay == "auto":
414 | new_disable_delay = 30
415 | else:
416 | new_disable_delay = disable_delay
417 | last_10_seconds = []
418 | attack_time = 0
419 | while True:
420 | time.sleep(1)
421 | try:
422 | if averaged_cpu_monitoring:
423 | current_cpu_usage = psutil.cpu_percent()
424 | logging.debug(f"Current CPU usage: {current_cpu_usage}%")
425 | last_10_seconds.append(current_cpu_usage)
426 | if len(last_10_seconds) > int(averaged_cpu_monitoring_range):
427 | last_10_seconds.pop(0)
428 | cpu_usage = sum(last_10_seconds) / len(last_10_seconds)
429 | logging.debug(f"Averaged CPU usage: {cpu_usage}%")
430 | else:
431 | cpu_usage = psutil.cpu_percent()
432 | logging.debug(f"Current CPU usage: {cpu_usage}%")
433 |
434 | if cpu_usage > int(cpu_threshold):
435 | t = 0
436 | logging.debug(f"CPU usage ({cpu_usage}%) exceeds threshold ({cpu_threshold}%), t = 0")
437 | else:
438 | t += 1
439 | logging.debug(f"CPU usage ({cpu_usage}%) is below threshold ({cpu_threshold}%), t = {t} (t+1)")
440 |
441 | if t > (int(new_disable_delay) * 2) and (disable_delay == "auto"):
442 | new_disable_delay = 30
443 | logging.debug(f"New disable delay: {new_disable_delay}")
444 |
445 | if t == 0 and rule_enabled:
446 | attack_time += 1
447 | logging.debug(f"Attack time: {attack_time}")
448 |
449 | if attack_time > 10:
450 | if discord_webhook:
451 | webhook = DiscordWebhook(url=discord_webhook, content=discord_custom_message_10_seconds)
452 | webhook.execute()
453 | logging.debug(f"Discord webhook executed (10 seconds after attack started)")
454 | if slack_webhook:
455 | webhook = WebhookClient(slack_webhook)
456 | webhook.send(text=slack_custom_message_10_seconds)
457 | logging.debug(f"Slack webhook executed (10 seconds after attack started)")
458 | if telegram_bot_token:
459 | send_telegram_message(telegram_custom_message_10_seconds, telegram_chat_id, telegram_bot_token)
460 | logging.debug(f"Telegram webhook executed (10 seconds after attack started)")
461 | attack_time = 0
462 | logging.debug(f"Attack time reset to 0")
463 |
464 | if t == 0 and not rule_enabled:
465 | logging.info(f"CPU usage ({cpu_usage}%) exceeds threshold ({cpu_threshold}%)")
466 | cf.rulesets.rules.edit(
467 | rule_id=rule_id,
468 | ruleset_id=ruleset_id,
469 | zone_id=zone_id,
470 | enabled=True
471 | )
472 | rule_enabled = True
473 | logging.info("Challenge rule enabled!")
474 |
475 | if disable_delay == "auto":
476 | logging.debug(f"Disable delay is auto, multiplying by 1.5 (new disable delay rn: {new_disable_delay})")
477 | new_disable_delay = int(new_disable_delay) * 1.5
478 | logging.debug(f"New disable delay: {new_disable_delay}")
479 |
480 | if discord_webhook:
481 | webhook = DiscordWebhook(url=discord_webhook, content=discord_custom_message)
482 | webhook.execute()
483 | logging.debug(f"Discord webhook executed (attack started)")
484 |
485 | if slack_webhook:
486 | webhook = WebhookClient(slack_webhook)
487 | webhook.send(text=slack_custom_message)
488 | logging.debug(f"Slack webhook executed (attack started)")
489 |
490 | if telegram_bot_token:
491 | send_telegram_message(telegram_custom_message, telegram_chat_id, telegram_bot_token)
492 | logging.debug(f"Telegram webhook executed (attack started)")
493 |
494 | elif t > int(new_disable_delay) and rule_enabled:
495 | logging.info("CPU usage returned to normal, disabling challenge rule...")
496 | cf.rulesets.rules.edit(
497 | rule_id=rule_id,
498 | ruleset_id=ruleset_id,
499 | zone_id=zone_id,
500 | enabled=False
501 | )
502 | rule_enabled = False
503 | logging.info("Challenge rule disabled!")
504 |
505 | if discord_webhook:
506 | webhook = DiscordWebhook(url=discord_webhook, content=discord_custom_message_end)
507 | webhook.execute()
508 | logging.debug(f"Discord webhook executed (attack ended)")
509 | if slack_webhook:
510 | webhook = WebhookClient(slack_webhook)
511 | webhook.send(text=slack_custom_message_end)
512 | logging.debug(f"Slack webhook executed (attack ended)")
513 | if telegram_bot_token:
514 | send_telegram_message(telegram_custom_message_end, telegram_chat_id, telegram_bot_token)
515 | logging.debug(f"Telegram webhook executed (attack ended)")
516 |
517 | except KeyboardInterrupt:
518 | logging.info("\nMonitoring stopped by user")
519 | break
520 | except Exception as e:
521 | logging.error(f"Error during monitoring: {e}")
522 | break
523 |
524 |
525 | def run():
526 | print(r"""
527 | /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$
528 | /$$__ $$| $$_____/ /$$__ $$| $$ |__/ | $$ | $$
529 | | $$ \__/| $$ | $$ \__/| $$$$$$$ /$$ /$$$$$$ | $$ /$$$$$$$
530 | | $$ | $$$$$ /$$$$$$| $$$$$$ | $$__ $$| $$ /$$__ $$| $$ /$$__ $$
531 | | $$ | $$__/|______/ \____ $$| $$ \ $$| $$| $$$$$$$$| $$| $$ | $$
532 | | $$ $$| $$ /$$ \ $$| $$ | $$| $$| $$_____/| $$| $$ | $$
533 | | $$$$$$/| $$ | $$$$$$/| $$ | $$| $$| $$$$$$$| $$| $$$$$$$
534 | \______/ |__/ \______/ |__/ |__/|__/ \_______/|__/ \_______/
535 |
536 |
537 |
538 | """)
539 | try:
540 | load_dotenv()
541 | if os.getenv("SETUP") == "true":
542 | logging.info("Configuration found, starting monitoring...")
543 | main()
544 | else:
545 | raise Exception("Setup not completed")
546 | except Exception:
547 | print(f"Welcome to CF-Shield, we will now set it up for you.")
548 | setup()
549 |
550 |
551 | if __name__ == "__main__":
552 | logger = logging.getLogger()
553 | if os.getenv("DEBUG") == "true":
554 | logger.setLevel(logging.DEBUG)
555 | else:
556 | logger.setLevel(logging.INFO)
557 |
558 | console_handler = logging.StreamHandler()
559 | if os.getenv("DEBUG") == "true":
560 | console_handler.setLevel(logging.DEBUG)
561 | else:
562 | console_handler.setLevel(logging.INFO)
563 |
564 | formatter = ColoredFormatter(
565 | "%(log_color)s%(asctime)s - %(levelname)s - %(message)s",
566 | datefmt="%Y-%m-%d %H:%M:%S",
567 | log_colors={
568 | 'DEBUG': 'cyan',
569 | 'INFO': 'green',
570 | 'WARNING': 'yellow',
571 | 'ERROR': 'red',
572 | 'CRITICAL': 'red,bg_white',
573 | }
574 | )
575 |
576 | console_handler.setFormatter(formatter)
577 | logger.addHandler(console_handler)
578 |
579 | if len(sys.argv) > 1 and sys.argv[1] == "setup":
580 | setup()
581 | else:
582 | run()
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/python-package/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import sys
4 | import json
5 | try:
6 | import requests
7 | import psutil
8 | from cloudflare import Cloudflare
9 | from discord_webhook import DiscordWebhook
10 | import time
11 | import logging
12 | import colorlog
13 | from colorlog import ColoredFormatter
14 | from slack_sdk.webhook import WebhookClient
15 | from ntfy import Ntfy
16 | except ImportError:
17 | print("installing dependencies...")
18 | os.system(f"{sys.executable} -m pip install -r requirements.txt")
19 |
20 |
21 | class Config:
22 | def __init__(self):
23 | self.cloudflare = {
24 | 'email': None,
25 | 'api_token': None,
26 | 'zone_id': None,
27 | 'account_id': None,
28 | 'ruleset_id': None,
29 | 'rule_id': None,
30 | 'challenge_type': 'managed_challenge'
31 | }
32 |
33 | self.domains = ['all']
34 |
35 | self.thresholds = {
36 | 'cpu': 80,
37 | 'ingoing_bandwidth': 50000000, # 50Mbps in bps
38 | 'outgoing_bandwidth': 50000000, # 50Mbps in bps
39 | }
40 |
41 | self.monitoring = {
42 | 'averaged_cpu': True,
43 | 'averaged_cpu_range': 10,
44 | 'enable_bandwidth_monitoring': False,
45 | 'disable_delay': 30
46 | }
47 |
48 | self.platforms = {
49 | 'slack': {
50 | 'enabled': False,
51 | 'webhook': None
52 | },
53 | 'discord': {
54 | 'enabled': False,
55 | 'webhook': None
56 | },
57 | 'telegram': {
58 | 'enabled': False,
59 | 'bot_token': None,
60 | 'chat_id': None
61 | },
62 | 'ntfy': {
63 | 'enabled': False,
64 | 'topic': None
65 | }
66 | }
67 |
68 | self.message_templates = {
69 | 'cpu': {
70 | 'attack_start': {
71 | 'default': "CPU Attack Detected!\nCPU Usage: {cpu_usage:.1f}% (Threshold: {cpu_threshold}%)\nDomains: {', '.join(domains)}\nTime: {timestamp}",
72 | 'slack': None,
73 | 'discord': None,
74 | 'telegram': None,
75 | 'ntfy': None
76 | },
77 | 'attack_end': {
78 | 'default': "CPU Attack Ended!\nCPU Usage: {cpu_usage:.1f}% (Normal)\nDomains: {', '.join(domains)}\nTime: {timestamp}",
79 | 'slack': None,
80 | 'discord': None,
81 | 'telegram': None,
82 | 'ntfy': None
83 | },
84 | 'attack_persist': {
85 | 'default': "CPU Attack Persisting!\nCPU Usage: {cpu_usage:.1f}% (Still High)\nDuration: 10+ seconds\nDomains: {', '.join(domains)}\nTime: {timestamp}",
86 | 'slack': None,
87 | 'discord': None,
88 | 'telegram': None,
89 | 'ntfy': None
90 | }
91 | },
92 | 'bandwidth_incoming': {
93 | 'attack_start': {
94 | 'default': "Incoming Bandwidth Attack!\nBandwidth: {incoming_bandwidth_mbps:.1f} Mbps (Limit: {incoming_limit_mbps:.1f} Mbps)\nDomains: {', '.join(domains)}\nTime: {timestamp}",
95 | 'slack': None,
96 | 'discord': None,
97 | 'telegram': None,
98 | 'ntfy': None
99 | },
100 | 'attack_end': {
101 | 'default': "Incoming Bandwidth Normal!\nBandwidth: {incoming_bandwidth_mbps:.1f} Mbps\nDomains: {', '.join(domains)}\nTime: {timestamp}",
102 | 'slack': None,
103 | 'discord': None,
104 | 'telegram': None,
105 | 'ntfy': None
106 | },
107 | 'attack_persist': {
108 | 'default': "Incoming Bandwidth Still High!\nBandwidth: {incoming_bandwidth_mbps:.1f} Mbps\nDuration: 10+ seconds\nDomains: {', '.join(domains)}\nTime: {timestamp}",
109 | 'slack': None,
110 | 'discord': None,
111 | 'telegram': None,
112 | 'ntfy': None
113 | }
114 | },
115 | 'bandwidth_outgoing': {
116 | 'attack_start': {
117 | 'default': "Outgoing Bandwidth Attack!\nBandwidth: {outgoing_bandwidth_mbps:.1f} Mbps (Limit: {outgoing_limit_mbps:.1f} Mbps)\nDomains: {', '.join(domains)}\nTime: {timestamp}",
118 | 'slack': None,
119 | 'discord': None,
120 | 'telegram': None,
121 | 'ntfy': None
122 | },
123 | 'attack_end': {
124 | 'default': "Outgoing Bandwidth Normal!\nBandwidth: {outgoing_bandwidth_mbps:.1f} Mbps\nDomains: {', '.join(domains)}\nTime: {timestamp}",
125 | 'slack': None,
126 | 'discord': None,
127 | 'telegram': None,
128 | 'ntfy': None
129 | },
130 | 'attack_persist': {
131 | 'default': "Outgoing Bandwidth Still High!\nBandwidth: {outgoing_bandwidth_mbps:.1f} Mbps\nDuration: 10+ seconds\nDomains: {', '.join(domains)}\nTime: {timestamp}",
132 | 'slack': None,
133 | 'discord': None,
134 | 'telegram': None,
135 | 'ntfy': None
136 | }
137 | }
138 | }
139 | self.setup_completed = False
140 | self.logging_level = logging.INFO
141 | self.config_file = "config.json"
142 |
143 | config = Config()
144 |
145 | def setup_domains():
146 | print("What's the domain(s) you want to use? (default: all, e.g. \"example.com,www.example.com\" or \"example.com\")")
147 | domains = input().strip().split(",")
148 | if not domains:
149 | domains = ["all"]
150 | else:
151 | if domains[0] != "all":
152 | for domain in domains:
153 | if domain.strip() == "":
154 | logging.error("No domain provided, please provide a domain")
155 | return
156 | elif not re.match(r"^((?!-)[A-Za-z0-9-]{1,63}(? 100:
212 | logging.error("CPU threshold cannot be greater than 100")
213 | return
214 | elif int(cpu_threshold) < 10:
215 | logging.error("You have set the CPU threshold to a very low value, if you know what you are doing, you can ignore this message")
216 | elif int(cpu_threshold) <= 0:
217 | logging.error("CPU threshold cannot be less than or equal to 0")
218 | return
219 | logging.debug(f"CPU threshold: {cpu_threshold}")
220 | return int(cpu_threshold)
221 |
222 | def setup_challenge_type():
223 | print("What's the challenge type you want to use? (default: managed_challenge, options: managed_challenge, js_challenge, challenge)")
224 | challenge_type = input().strip()
225 | if not challenge_type:
226 | challenge_type = "managed_challenge"
227 | elif challenge_type not in ["managed_challenge", "js_challenge", "challenge"]:
228 | logging.error("Invalid challenge type, please enter a valid challenge type")
229 | return
230 | logging.debug(f"Challenge type: {challenge_type}")
231 | return challenge_type
232 |
233 | def setup_slack_webhook(domains):
234 | print("If you want to use a Slack webhook, please enter the webhook URL (default: None)")
235 | slack_webhook = input().strip()
236 | if not slack_webhook:
237 | return None, None, None, None
238 | else:
239 | if not re.match(r"^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9\/]+$", slack_webhook):
240 | logging.error("Invalid Slack webhook URL, please enter a valid Slack webhook URL")
241 | return None, None, None, None
242 | else:
243 | logging.info("Sending a test message to the Slack webhook...")
244 | try:
245 | webhook = WebhookClient(slack_webhook)
246 | webhook.send(text="Test message from CF-Shield")
247 | logging.info("Test message sent successfully!")
248 | except Exception as e:
249 | logging.error(f"Error sending test message to Slack webhook: {e}")
250 | return None, None, None, None
251 | else:
252 | print(f"If you want to use a custom message for the attack start, please enter the message (default: {config.message_templates['cpu']['attack_start']['default']})")
253 | slack_custom_message = input().strip()
254 | if not slack_custom_message:
255 | slack_custom_message = config.message_templates['cpu']['attack_start']['default']
256 | print(f"If you want to use a custom message for the attack end, please enter the message (default: {config.message_templates['cpu']['attack_end']['default']})")
257 | slack_custom_message_end = input().strip()
258 | if not slack_custom_message_end:
259 | slack_custom_message_end = config.message_templates['cpu']['attack_end']['default']
260 | print(f"If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: {config.message_templates['cpu']['attack_persist']['default']})")
261 | slack_custom_message_10_seconds = input().strip()
262 | if not slack_custom_message_10_seconds:
263 | slack_custom_message_10_seconds = config.message_templates['cpu']['attack_persist']['default']
264 | logging.debug(f"Slack webhook: {slack_webhook}")
265 | logging.debug(f"Slack custom message: {slack_custom_message}")
266 | logging.debug(f"Slack custom message end: {slack_custom_message_end}")
267 | logging.debug(f"Slack custom message 10 seconds: {slack_custom_message_10_seconds}")
268 | return slack_webhook, slack_custom_message, slack_custom_message_end, slack_custom_message_10_seconds
269 |
270 | def setup_discord_webhook(domains):
271 | print("If you want to use a Discord webhook, please enter the webhook URL (default: None)")
272 | discord_webhook = input().strip()
273 | if not discord_webhook:
274 | return None, None, None, None
275 | else:
276 | if not re.match(r"^https:\/\/(discord\.com|ptb\.discord\.com|canary\.discord\.com)\/api\/webhooks\/[0-9]+\/[a-zA-Z0-9-]+$", discord_webhook):
277 | logging.error("Invalid Discord webhook URL, please enter a valid Discord webhook URL")
278 | return None, None, None, None
279 | else:
280 | logging.info("Sending a test message to the Discord webhook...")
281 | try:
282 | webhook = DiscordWebhook(url=discord_webhook, content="Test message from CF-Shield")
283 | webhook.execute()
284 | logging.info("Test message sent successfully!")
285 | except Exception as e:
286 | logging.error(f"Error sending test message to Discord webhook: {e}")
287 | return None, None, None, None
288 | else:
289 | print(f"If you want to use a custom message for the attack start, please enter the message (default: {config.message_templates['cpu']['attack_start']['default']})")
290 | discord_custom_message = input().strip()
291 | if not discord_custom_message:
292 | discord_custom_message = config.message_templates['cpu']['attack_start']['default']
293 | print(f"If you want to use a custom message for the attack end, please enter the message (default: {config.message_templates['cpu']['attack_end']['default']})")
294 | discord_custom_message_end = input().strip()
295 | if not discord_custom_message_end:
296 | discord_custom_message_end = config.message_templates['cpu']['attack_end']['default']
297 | print(f"If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: {config.message_templates['cpu']['attack_persist']['default']})")
298 | discord_custom_message_10_seconds = input().strip()
299 | if not discord_custom_message_10_seconds:
300 | discord_custom_message_10_seconds = config.message_templates['cpu']['attack_persist']['default']
301 | logging.debug(f"Discord webhook: {discord_webhook}")
302 | logging.debug(f"Discord custom message: {discord_custom_message}")
303 | logging.debug(f"Discord custom message end: {discord_custom_message_end}")
304 | logging.debug(f"Discord custom message 10 seconds: {discord_custom_message_10_seconds}")
305 | return discord_webhook, discord_custom_message, discord_custom_message_end, discord_custom_message_10_seconds
306 |
307 | def setup_telegram_bot(domains):
308 | print("If you want to use a Telegram bot, please enter the bot token (default: None)")
309 | telegram_bot_token = input().strip()
310 | if not telegram_bot_token:
311 | return None, None, None, None, None
312 | else:
313 | if not re.match(r"([0-9]{8,10}):[A-za-z0-9]{35}", telegram_bot_token):
314 | logging.error("Invalid Telegram bot token, please enter a valid Telegram bot token")
315 | return None, None, None, None, None
316 | print("Please enter the chat ID for the telegram bot")
317 | telegram_chat_id = input().strip()
318 | if not re.match(r"^[0-9]+$", telegram_chat_id):
319 | logging.error("Invalid Telegram chat ID, please enter a valid Telegram chat ID")
320 | return None, None, None, None, None
321 | else:
322 | logging.info("Sending a test message to the Telegram bot...")
323 | try:
324 | send_telegram_message("Test message from CF-Shield", telegram_chat_id, telegram_bot_token)
325 | logging.info("Test message sent successfully!")
326 | except Exception as e:
327 | logging.error(f"Error sending test message to Telegram bot: {e}")
328 | return None, None, None, None, None
329 | else:
330 | print(f"If you want to use a custom message for the attack start, please enter the message (default: {config.message_templates['cpu']['attack_start']['default']})")
331 | telegram_custom_message = input().strip()
332 | if not telegram_custom_message:
333 | telegram_custom_message = config.message_templates['cpu']['attack_start']['default']
334 | print(f"If you want to use a custom message for the attack end, please enter the message (default: {config.message_templates['cpu']['attack_end']['default']})")
335 | telegram_custom_message_end = input().strip()
336 | if not telegram_custom_message_end:
337 | telegram_custom_message_end = config.message_templates['cpu']['attack_end']['default']
338 | print(f"If you want to use a custom message for when the CPU usage is too high 10 seconds after the attack started, please enter the message (default: {config.message_templates['cpu']['attack_persist']['default']})")
339 | telegram_custom_message_10_seconds = input().strip()
340 | if not telegram_custom_message_10_seconds:
341 | telegram_custom_message_10_seconds = config.message_templates['cpu']['attack_persist']['default']
342 | logging.debug(f"Telegram bot token: {telegram_bot_token}")
343 | logging.debug(f"Telegram chat ID: {telegram_chat_id}")
344 | logging.debug(f"Telegram custom message: {telegram_custom_message}")
345 | logging.debug(f"Telegram custom message end: {telegram_custom_message_end}")
346 | logging.debug(f"Telegram custom message 10 seconds: {telegram_custom_message_10_seconds}")
347 | return telegram_bot_token, telegram_chat_id, telegram_custom_message, telegram_custom_message_end, telegram_custom_message_10_seconds
348 |
349 | def setup_disable_delay():
350 | print("How many seconds do you want to wait before disabling the challenge rule? (default: auto eg. 30)")
351 | disable_delay = input().strip()
352 | if not disable_delay:
353 | return "auto"
354 | elif disable_delay == "auto":
355 | return "auto"
356 | elif not re.match(r"^[0-9]+$", disable_delay):
357 | logging.error("Invalid disable delay, please enter a valid disable delay")
358 | return None
359 | elif int(disable_delay) < 0:
360 | logging.error("Disable delay cannot be less than 0")
361 | return None
362 | elif int(disable_delay) < 5:
363 | logging.error("You have set the disable delay to a very low value, if you know what you are doing, you can ignore this message")
364 | elif int(disable_delay) > 1800:
365 | logging.error("You have set the disable delay to a very high value, if you know what you are doing, you can ignore this message")
366 | logging.debug(f"Disable delay: {disable_delay}")
367 | return int(disable_delay)
368 |
369 | def setup_averaged_cpu_monitoring():
370 | print("Do you want to use averaged CPU monitoring? (default: yes)")
371 | averaged_cpu_monitoring = input().strip().lower()
372 | if not averaged_cpu_monitoring:
373 | averaged_cpu_monitoring = True
374 | elif averaged_cpu_monitoring in ["true", "yes", "y"]:
375 | averaged_cpu_monitoring = True
376 | elif averaged_cpu_monitoring in ["false", "no", "n"]:
377 | averaged_cpu_monitoring = False
378 | else:
379 | logging.error("Invalid averaged CPU monitoring, setting to default (yes)")
380 | averaged_cpu_monitoring = True
381 | logging.debug(f"Averaged CPU monitoring: {averaged_cpu_monitoring}")
382 | return averaged_cpu_monitoring
383 |
384 | def setup_averaged_cpu_monitoring_range():
385 | print("Please enter the range of the averaged CPU monitoring (default: 10)")
386 | averaged_cpu_monitoring_range = input().strip()
387 | if not averaged_cpu_monitoring_range:
388 | averaged_cpu_monitoring_range = 10
389 | elif not re.match(r"^[0-9]+$", averaged_cpu_monitoring_range):
390 | logging.error("Invalid averaged CPU monitoring range, setting to default (10)")
391 | averaged_cpu_monitoring_range = 10
392 | elif int(averaged_cpu_monitoring_range) < 2:
393 | logging.error("Averaged CPU monitoring range cannot be less than 2")
394 | return None
395 | elif int(averaged_cpu_monitoring_range) > 120:
396 | logging.warning("Averaged CPU monitoring range is too high, you can ignore this message if you know what you are doing")
397 | logging.debug(f"Averaged CPU monitoring range: {averaged_cpu_monitoring_range}")
398 | return int(averaged_cpu_monitoring_range)
399 |
400 |
401 | def setup_enable_bandwidth_monitoring():
402 | print("Do you want to use bandwidth monitoring? (default: no)")
403 | enable_bandwidth_monitoring = input().strip().lower()
404 | if not enable_bandwidth_monitoring:
405 | enable_bandwidth_monitoring = False
406 | elif enable_bandwidth_monitoring in ["true", "yes", "y"]:
407 | enable_bandwidth_monitoring = True
408 | elif enable_bandwidth_monitoring in ["false", "no", "n"]:
409 | enable_bandwidth_monitoring = False
410 | else:
411 | logging.error("Invalid enable bandwidth monitoring, setting to default (no)")
412 | enable_bandwidth_monitoring = False
413 | logging.debug(f"Enable bandwidth monitoring: {enable_bandwidth_monitoring}")
414 | if enable_bandwidth_monitoring:
415 | print("Please enter the ingoing limit with the unit, no unit means bits per second (default: 50000000, 50Mbps)")
416 | ingoing_limit = input().strip()
417 | ingoing_limit = setup_ingoing_limit(ingoing_limit)
418 | print("Please enter the outgoing limit with the unit, no unit means bits per second (default: 50000000, 50Mbps)")
419 | outgoing_limit = input().strip()
420 | outgoing_limit = setup_outgoing_limit(outgoing_limit)
421 | return True,ingoing_limit, outgoing_limit
422 | else:
423 | return False, None, None
424 |
425 | def setup_ingoing_limit(ingoing_limit):
426 | multiplier = 1
427 | new_ingoing_limit = ""
428 | if not ingoing_limit:
429 | return int(50000000) #50Mbps
430 | else:
431 | for char in ingoing_limit:
432 | if char.isdigit():
433 | new_ingoing_limit += str(char)
434 | elif char == "B":
435 | multiplier = multiplier * 8
436 | elif char == "b":
437 | continue
438 | elif char.lower() == "k":
439 | multiplier = multiplier * 1000
440 | elif char.lower() == "m":
441 | multiplier = multiplier * 1000000
442 | elif char.lower() == "g":
443 | multiplier = multiplier * 1000000000
444 | elif char == "/":
445 | continue
446 | elif char.lower() == "s":
447 | continue
448 | elif char.lower() == "p":
449 | continue
450 | else:
451 | logging.error("Invalid ingoing limit, setting to default (50Mbps)")
452 | return int(50000000)
453 |
454 | if new_ingoing_limit:
455 | ingoing_limit = int(new_ingoing_limit) * multiplier
456 | else:
457 | return int(50000000) #50Mbps
458 | logging.debug(f"Ingoing limit: {ingoing_limit}bps")
459 | return int(ingoing_limit)
460 |
461 | def setup_outgoing_limit(outgoing_limit):
462 | multiplier = 1
463 | new_outgoing_limit = ""
464 | if not outgoing_limit:
465 | return int(50000000) #50Mbps
466 | else:
467 | for char in outgoing_limit:
468 | if char.isdigit():
469 | new_outgoing_limit += str(char)
470 | elif char == "B":
471 | multiplier = multiplier * 8
472 | elif char == "b":
473 | continue
474 | elif char.lower() == "k":
475 | multiplier = multiplier * 1000
476 | elif char.lower() == "m":
477 | multiplier = multiplier * 1000000
478 | elif char.lower() == "g":
479 | multiplier = multiplier * 1000000000
480 | elif char == "/":
481 | continue
482 | elif char.lower() == "s":
483 | continue
484 | elif char.lower() == "p":
485 | continue
486 | else:
487 | logging.error("Invalid outgoing limit, setting to default (50Mbps)")
488 | return int(50000000)
489 |
490 | if new_outgoing_limit:
491 | outgoing_limit = int(new_outgoing_limit) * multiplier
492 | else:
493 | return int(50000000) #50Mbps
494 | logging.debug(f"Outgoing limit: {outgoing_limit}bps")
495 | return int(outgoing_limit)
496 |
497 | def setup():
498 | while True:
499 | try:
500 | config.domains = setup_domains()
501 | if config.domains is not None:
502 | break
503 | logging.error("Please try again")
504 | except Exception as e:
505 | logging.error(f"Error setting up domains: {e}, please try again")
506 | continue
507 |
508 | while True:
509 | try:
510 | config.cloudflare['email'] = setup_email()
511 | if config.cloudflare['email'] is not None:
512 | break
513 | logging.error("Please try again")
514 | except Exception as e:
515 | logging.error(f"Error setting up email: {e}, please try again")
516 | continue
517 |
518 | while True:
519 | try:
520 | config.cloudflare['api_token'] = setup_api_token()
521 | if config.cloudflare['api_token'] is not None:
522 | break
523 | logging.error("Please try again")
524 | except Exception as e:
525 | logging.error(f"Error setting up API token: {e}, please try again")
526 | continue
527 |
528 | while True:
529 | try:
530 | config.cloudflare['zone_id'] = setup_zone_id()
531 | if config.cloudflare['zone_id'] is None:
532 | logging.error("Please try again")
533 | continue
534 | except Exception as e:
535 | logging.error(f"Error setting up zone ID: {e}, please try again")
536 | continue
537 | try:
538 | config.cloudflare['account_id'] = setup_account_id(config.cloudflare['zone_id'])
539 | if config.cloudflare['account_id'] is None:
540 | logging.error("Please try again, you will be sent back to setting up the zone ID in case you made a mistake")
541 | continue
542 | except Exception as e:
543 | logging.error(f"Error setting up account ID: {e}, please try again")
544 | continue
545 |
546 | break
547 | while True:
548 | try:
549 | config.thresholds['cpu'] = setup_cpu_threshold()
550 | if config.thresholds['cpu'] is not None:
551 | break
552 | logging.error("Please try again")
553 | except Exception as e:
554 | logging.error(f"Error setting up CPU threshold: {e}, please try again")
555 | continue
556 |
557 | while True:
558 | try:
559 | config.cloudflare['challenge_type'] = setup_challenge_type()
560 | if config.cloudflare['challenge_type'] is not None:
561 | break
562 | logging.error("Please try again")
563 | except Exception as e:
564 | logging.error(f"Error setting up challenge type: {e}, please try again")
565 | continue
566 |
567 | while True:
568 | try:
569 | config.platforms['slack']['webhook'], config.message_templates['cpu']['attack_start']['slack'], config.message_templates['cpu']['attack_end']['slack'], config.message_templates['cpu']['attack_persist']['slack'] = setup_slack_webhook(config.domains)
570 | if config.platforms['slack']['webhook'] is not None:
571 | break
572 | logging.error("Please try again")
573 | except Exception as e:
574 | logging.error(f"Error setting up Slack webhook: {e}, please try again")
575 | continue
576 |
577 | while True:
578 | try:
579 | config.platforms['discord']['webhook'], config.message_templates['cpu']['attack_start']['discord'], config.message_templates['cpu']['attack_end']['discord'], config.message_templates['cpu']['attack_persist']['discord'] = setup_discord_webhook(config.domains)
580 | if config.platforms['discord']['webhook'] is not None:
581 | break
582 | logging.error("Please try again")
583 | except Exception as e:
584 | logging.error(f"Error setting up Discord webhook: {e}, please try again")
585 | continue
586 |
587 | while True:
588 | try:
589 | config.platforms['telegram']['bot_token'], config.platforms['telegram']['chat_id'], config.message_templates['cpu']['attack_start']['telegram'], config.message_templates['cpu']['attack_end']['telegram'], config.message_templates['cpu']['attack_persist']['telegram'] = setup_telegram_bot(config.domains)
590 | if config.platforms['telegram']['bot_token'] is not None:
591 | break
592 | logging.error("Please try again")
593 | except Exception as e:
594 | logging.error(f"Error setting up Telegram bot: {e}, please try again")
595 | continue
596 |
597 | while True:
598 | try:
599 | config.monitoring['disable_delay'] = setup_disable_delay()
600 | if config.monitoring['disable_delay'] is not None:
601 | break
602 | logging.error("Please try again")
603 | except Exception as e:
604 | logging.error(f"Error setting up disable delay: {e}, please try again")
605 | continue
606 |
607 | while True:
608 | try:
609 | config.monitoring['averaged_cpu'] = setup_averaged_cpu_monitoring()
610 | if config.monitoring['averaged_cpu'] is not None:
611 | break
612 | logging.error("Please try again")
613 | except Exception as e:
614 | logging.error(f"Error setting up averaged CPU monitoring: {e}, please try again")
615 | continue
616 |
617 | while True:
618 | try:
619 | config.monitoring['averaged_cpu_range'] = setup_averaged_cpu_monitoring_range()
620 | if config.monitoring['averaged_cpu_range'] is not None:
621 | break
622 | logging.error("Please try again")
623 | except Exception as e:
624 | logging.error(f"Error setting up averaged CPU monitoring range: {e}, please try again")
625 | continue
626 |
627 | while True:
628 | try:
629 | config.monitoring['enable_bandwidth_monitoring'], config.monitoring['ingoing_limit'], config.monitoring['outgoing_limit'] = setup_enable_bandwidth_monitoring()
630 | if config.monitoring['enable_bandwidth_monitoring']:
631 | if config.monitoring['ingoing_limit'] is None or config.monitoring['outgoing_limit'] is None:
632 | logging.error("Please try again")
633 | continue
634 | else:
635 | break
636 | else:
637 | break
638 | except Exception as e:
639 | logging.error(f"Error setting up bandwidth monitoring: {e}, please try again")
640 | continue
641 |
642 | cf = Cloudflare(api_token=config.cloudflare['api_token'])
643 |
644 | try:
645 | rulesets_page = cf.rulesets.list(zone_id=config.cloudflare['zone_id'])
646 | logging.debug(f"Rulesets: {rulesets_page}")
647 |
648 | target_ruleset_id = None
649 | for ruleset in rulesets_page.result:
650 | if ruleset.phase == "http_request_firewall_custom":
651 | target_ruleset_id = ruleset.id
652 | break
653 | logging.debug(f"Target ruleset ID: {target_ruleset_id}")
654 |
655 | if not target_ruleset_id:
656 | logging.info("No http_request_firewall_custom ruleset found.")
657 |
658 | custom_ruleset = cf.rulesets.create(
659 | kind="zone",
660 | name="cf-shield-challenge",
661 | phase="http_request_firewall_custom",
662 | zone_id=config.cloudflare['zone_id']
663 | )
664 | target_ruleset_id = custom_ruleset.id
665 | logging.debug(f"Target ruleset ID: {target_ruleset_id}")
666 |
667 | existing_ruleset = cf.rulesets.get(zone_id=config.cloudflare['zone_id'], ruleset_id=target_ruleset_id)
668 | logging.debug(f"Existing ruleset: {existing_ruleset}")
669 |
670 | cf_shield_rule_id = None
671 | try:
672 | for rule in existing_ruleset.rules:
673 | if rule.description and "CF-Shield" in rule.description:
674 | cf_shield_rule_id = rule.id
675 | break
676 | except Exception as e:
677 | logging.error(f"Error checking for existing CF-Shield rule: {e}")
678 | cf_shield_rule_id = None
679 | logging.debug(f"CF-Shield rule ID: {cf_shield_rule_id}")
680 |
681 | if not cf_shield_rule_id:
682 | expression = "("
683 | if config.domains[0] != "all":
684 | for domain in config.domains:
685 | expression += f"http.host eq \"{domain}\" or "
686 | expression = expression[:-4] + ")"
687 | else:
688 | expression = "(http.host ne \"example.invalid\")"
689 | new_rule = cf.rulesets.rules.create(
690 | ruleset_id=target_ruleset_id,
691 | zone_id=config.cloudflare['zone_id'],
692 | action=config.cloudflare['challenge_type'],
693 | expression=expression,
694 | description="CF-Shield",
695 | enabled=False
696 | )
697 | cf_shield_rule_id = new_rule.id
698 | logging.debug(f"CF-Shield rule ID: {cf_shield_rule_id}")
699 |
700 | print(f"Setup successful!")
701 | print(f" Ruleset ID: {config.cloudflare['ruleset_id']}")
702 | print(f" Rule ID: {config.cloudflare['rule_id']}")
703 |
704 | except Exception as e:
705 | logging.error(f"Error working with rulesets: {e}")
706 | logging.error("Note: You may need to adjust your API token permissions.")
707 | return None
708 |
709 | config.cloudflare['ruleset_id'] = target_ruleset_id
710 | config.cloudflare['rule_id'] = cf_shield_rule_id
711 | config.setup_completed = True
712 |
713 | print("Saving configuration to config.json file...")
714 | try:
715 | with open(config.config_file, "w") as f:
716 | json.dump(config.__dict__, f, indent=2)
717 | print("Configuration saved successfully!")
718 | except Exception as e:
719 | logging.error(f"Error saving configuration: {e}")
720 | return None
721 |
722 | print("Setup complete! Starting monitoring...")
723 | main()
724 |
725 | def send_telegram_message(message, telegram_chat_id, telegram_bot_token):
726 | try:
727 | url = f"https://api.telegram.org/bot{telegram_bot_token}/sendMessage"
728 | data = {
729 | "chat_id": telegram_chat_id,
730 | "text": message
731 | }
732 | requests.post(url, json=data)
733 | except Exception as e:
734 | logging.error(f"Failed to send Telegram message: {e}")
735 |
736 | def notify(message, slack_webhook=None, discord_webhook=None, telegram_bot_token=None, telegram_chat_id=None):
737 | if slack_webhook:
738 | webhook = WebhookClient(slack_webhook)
739 | webhook.send(text=message)
740 | logging.debug(f"Slack webhook executed (notify)")
741 | if discord_webhook:
742 | webhook = DiscordWebhook(url=discord_webhook, content=message)
743 | webhook.execute()
744 | logging.debug(f"Discord webhook executed (notify)")
745 | if telegram_bot_token:
746 | send_telegram_message(message, telegram_chat_id, telegram_bot_token)
747 | logging.debug(f"Telegram webhook executed (notify)")
748 |
749 | def get_cpu_usage(averaged_cpu_monitoring, last_readings, averaged_cpu_monitoring_range):
750 | current_cpu_usage = psutil.cpu_percent()
751 |
752 | if averaged_cpu_monitoring:
753 | logging.debug(f"Current CPU usage: {current_cpu_usage}%")
754 | last_readings.append(current_cpu_usage)
755 | if len(last_readings) > int(averaged_cpu_monitoring_range):
756 | last_readings.pop(0)
757 | cpu_usage = sum(last_readings) / len(last_readings)
758 | logging.debug(f"Averaged CPU usage: {cpu_usage}%")
759 | return cpu_usage
760 | else:
761 | logging.debug(f"Current CPU usage: {current_cpu_usage}%")
762 | return current_cpu_usage
763 |
764 | def get_bandwidth_usage():
765 | stats = psutil.net_io_counters()
766 | current_ingoing_traffic = stats.bytes_recv
767 | current_outgoing_traffic = stats.bytes_sent
768 |
769 | logging.debug(f"Current ingoing traffic: {current_ingoing_traffic} bytes")
770 | logging.debug(f"Current outgoing traffic: {current_outgoing_traffic} bytes")
771 |
772 | return current_ingoing_traffic, current_outgoing_traffic
773 |
774 | def check_thresholds(cpu_usage, cpu_threshold, current_ingoing_traffic=None,
775 | ingoing_limit=None, current_outgoing_traffic=None, outgoing_limit=None):
776 | attack_detected = False
777 |
778 | # CPU
779 | if cpu_usage > int(cpu_threshold):
780 | logging.debug(f"CPU usage ({cpu_usage}%) exceeds threshold ({cpu_threshold}%)")
781 | attack_detected = True
782 | else:
783 | logging.debug(f"CPU usage ({cpu_usage}%) is below threshold ({cpu_threshold}%)")
784 |
785 | # Bandwidth
786 | if current_ingoing_traffic is not None and ingoing_limit is not None:
787 | if current_ingoing_traffic > ingoing_limit:
788 | logging.debug(f"Ingoing traffic ({current_ingoing_traffic} bytes) exceeds limit ({ingoing_limit} bytes)")
789 | attack_detected = True
790 | else:
791 | logging.debug(f"Ingoing traffic ({current_ingoing_traffic} bytes) is below limit ({ingoing_limit} bytes)")
792 |
793 | if current_outgoing_traffic is not None and outgoing_limit is not None:
794 | if current_outgoing_traffic > outgoing_limit:
795 | logging.debug(f"Outgoing traffic ({current_outgoing_traffic} bytes) exceeds limit ({outgoing_limit} bytes)")
796 | attack_detected = True
797 | else:
798 | logging.debug(f"Outgoing traffic ({current_outgoing_traffic} bytes) is below limit ({outgoing_limit} bytes)")
799 |
800 | return attack_detected
801 |
802 | def manage_cloudflare_rule(cf, rule_enabled, attack_detected, timer, disable_delay,
803 | rule_id, ruleset_id, zone_id, cpu_usage, cpu_threshold,
804 | discord_custom_message, discord_webhook, slack_custom_message,
805 | slack_webhook, telegram_custom_message, telegram_bot_token,
806 | telegram_chat_id, discord_custom_message_end,
807 | slack_custom_message_end, telegram_custom_message_end):
808 | new_rule_enabled = rule_enabled
809 |
810 | if attack_detected and not rule_enabled:
811 | logging.info(f"CPU usage ({cpu_usage}%) exceeds threshold ({cpu_threshold}%)")
812 | cf.rulesets.rules.edit(
813 | rule_id=rule_id,
814 | ruleset_id=ruleset_id,
815 | zone_id=zone_id,
816 | enabled=True
817 | )
818 | new_rule_enabled = True
819 | logging.info("Challenge rule enabled!")
820 |
821 | notify(discord_custom_message, discord_webhook)
822 | notify(slack_custom_message, slack_webhook)
823 | notify(telegram_custom_message, telegram_bot_token, telegram_chat_id)
824 |
825 | elif timer > int(disable_delay) and rule_enabled:
826 | logging.info("CPU usage returned to normal, disabling challenge rule...")
827 | cf.rulesets.rules.edit(
828 | rule_id=rule_id,
829 | ruleset_id=ruleset_id,
830 | zone_id=zone_id,
831 | enabled=False
832 | )
833 | new_rule_enabled = False
834 | logging.info("Challenge rule disabled!")
835 |
836 | notify(discord_custom_message_end, discord_webhook)
837 | notify(slack_custom_message_end, slack_webhook)
838 | notify(telegram_custom_message_end, telegram_bot_token, telegram_chat_id)
839 |
840 | return new_rule_enabled
841 |
842 | def update_timer_and_delay(attack_detected, timer, disable_delay, new_disable_delay):
843 | if attack_detected:
844 | new_timer = 0
845 | logging.debug(f"Attack detected, timer reset to 0")
846 |
847 | if disable_delay == "auto":
848 | updated_disable_delay = int(new_disable_delay) * 1.5
849 | logging.debug(f"Disable delay is auto, multiplying by 1.5 (new disable delay: {updated_disable_delay})")
850 | return new_timer, updated_disable_delay
851 | else:
852 | new_timer = timer + 1
853 | logging.debug(f"No attack detected, timer = {new_timer}")
854 |
855 | if new_timer > (int(new_disable_delay) * 2) and (disable_delay == "auto"):
856 | updated_disable_delay = 30
857 | logging.debug(f"Timer exceeded double delay, reset disable delay to: {updated_disable_delay}")
858 | return new_timer, updated_disable_delay
859 |
860 | return new_timer, new_disable_delay
861 |
862 | def main():
863 | cf = Cloudflare(api_token=config.cloudflare['api_token'])
864 |
865 | if not all([config.cloudflare['zone_id'], config.cloudflare['ruleset_id'], config.cloudflare['rule_id']]):
866 | logging.error("Missing configuration. Please run setup again.")
867 | logging.error(f"Zone ID: {config.cloudflare['zone_id']}")
868 | logging.error(f"Ruleset ID: {config.cloudflare['ruleset_id']}")
869 | logging.error(f"Rule ID: {config.cloudflare['rule_id']}")
870 | return None
871 |
872 | logging.info(f"Monitoring CPU usage for domains: {', '.join(config.domains)}")
873 | logging.info(f"CPU threshold: {config.thresholds['cpu']}%")
874 |
875 | # Initialize monitoring variables
876 | rule_enabled = False
877 | timer = 1
878 | new_disable_delay = 30 if config.monitoring['disable_delay'] == "auto" else config.monitoring['disable_delay']
879 | last_cpu_readings = []
880 | attack_time = 0
881 |
882 | while True:
883 | time.sleep(1)
884 | try:
885 | # Get CPU usage (averaged or direct)
886 | cpu_usage = get_cpu_usage(config.monitoring['averaged_cpu'], last_cpu_readings, config.monitoring['averaged_cpu_range'])
887 |
888 | # Get bandwidth usage if monitoring is enabled
889 | current_ingoing_traffic = None
890 | current_outgoing_traffic = None
891 | if hasattr(config.monitoring, 'enable_bandwidth_monitoring') and config.monitoring['enable_bandwidth_monitoring']:
892 | current_ingoing_traffic, current_outgoing_traffic = get_bandwidth_usage()
893 |
894 | # Check all thresholds
895 | attack_detected = check_thresholds(
896 | cpu_usage, config.thresholds['cpu'],
897 | current_ingoing_traffic, config.monitoring.get('ingoing_limit') if hasattr(config.monitoring, 'enable_bandwidth_monitoring') and config.monitoring['enable_bandwidth_monitoring'] else None,
898 | current_outgoing_traffic, config.monitoring.get('outgoing_limit') if hasattr(config.monitoring, 'enable_bandwidth_monitoring') and config.monitoring['enable_bandwidth_monitoring'] else None
899 | )
900 |
901 | # Update timer and disable delay
902 | timer, new_disable_delay = update_timer_and_delay(attack_detected, timer, config.monitoring['disable_delay'], new_disable_delay)
903 |
904 | # Track attack time for 10-second notification
905 | if attack_detected and rule_enabled:
906 | attack_time += 1
907 | logging.debug(f"Attack time: {attack_time}")
908 |
909 | if attack_time > 10:
910 | notify(config.message_templates['cpu']['attack_persist']['discord'], config.platforms['discord']['webhook'])
911 | notify(config.message_templates['cpu']['attack_persist']['slack'], config.platforms['slack']['webhook'])
912 | notify(config.message_templates['cpu']['attack_persist']['telegram'], config.platforms['telegram']['bot_token'], config.platforms['telegram']['chat_id'])
913 | attack_time = 0
914 | logging.debug(f"Attack time reset to 0")
915 | else:
916 | attack_time = 0
917 |
918 | # Manage Cloudflare rule
919 | rule_enabled = manage_cloudflare_rule(
920 | cf, rule_enabled, attack_detected, timer, new_disable_delay,
921 | config.cloudflare['rule_id'], config.cloudflare['ruleset_id'], config.cloudflare['zone_id'], cpu_usage, config.thresholds['cpu'],
922 | config.message_templates['cpu']['attack_start']['discord'], config.platforms['discord']['webhook'], config.message_templates['cpu']['attack_start']['slack'], config.platforms['slack']['webhook'],
923 | config.message_templates['cpu']['attack_start']['telegram'], config.platforms['telegram']['bot_token'], config.platforms['telegram']['chat_id'],
924 | config.message_templates['cpu']['attack_end']['discord'], config.platforms['discord']['webhook'], config.message_templates['cpu']['attack_end']['slack'], config.platforms['slack']['webhook'],
925 | config.message_templates['cpu']['attack_end']['telegram'], config.platforms['telegram']['bot_token'], config.platforms['telegram']['chat_id']
926 | )
927 |
928 | except KeyboardInterrupt:
929 | logging.info("\nMonitoring stopped by user")
930 | break
931 | except Exception as e:
932 | logging.error(f"Error during monitoring: {e}")
933 | break
934 |
935 |
936 | def run():
937 | print(r"""
938 | /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$
939 | /$$__ $$| $$_____/ /$$__ $$| $$ |__/ | $$ | $$
940 | | $$ \__/| $$ | $$ \__/| $$$$$$$ /$$ /$$$$$$ | $$ /$$$$$$$
941 | | $$ | $$$$$ /$$$$$$| $$$$$$ | $$__ $$| $$ /$$__ $$| $$ /$$__ $$
942 | | $$ | $$__/|______/ \____ $$| $$ \ $$| $$| $$$$$$$$| $$| $$ | $$
943 | | $$ $$| $$ /$$ \ $$| $$ | $$| $$| $$_____/| $$| $$ | $$
944 | | $$$$$$/| $$ | $$$$$$/| $$ | $$| $$| $$$$$$$| $$| $$$$$$$
945 | \______/ |__/ \______/ |__/ |__/|__/ \_______/|__/ \_______/
946 |
947 |
948 |
949 | """)
950 | try:
951 | with open(config.config_file, "r") as f:
952 | loaded_config = json.load(f)
953 |
954 | if loaded_config.get('setup_completed'):
955 | for key, value in loaded_config.items():
956 | if hasattr(config, key):
957 | setattr(config, key, value)
958 | logging.info("Configuration found, starting monitoring...")
959 | main()
960 | else:
961 | raise Exception("Setup not completed")
962 | except Exception:
963 | print(f"Welcome to CF-Shield, we will now set it up for you.")
964 | setup()
965 |
966 |
967 | if __name__ == "__main__":
968 | logger = logging.getLogger()
969 | if config.logging_level == "DEBUG":
970 | logger.setLevel(logging.DEBUG)
971 | else:
972 | logger.setLevel(logging.INFO)
973 |
974 | console_handler = logging.StreamHandler()
975 | if config.logging_level == "DEBUG":
976 | console_handler.setLevel(logging.DEBUG)
977 | else:
978 | console_handler.setLevel(logging.INFO)
979 |
980 | formatter = ColoredFormatter(
981 | "%(log_color)s%(asctime)s - %(levelname)s - %(message)s",
982 | datefmt="%Y-%m-%d %H:%M:%S",
983 | log_colors={
984 | 'DEBUG': 'cyan',
985 | 'INFO': 'green',
986 | 'WARNING': 'yellow',
987 | 'ERROR': 'red',
988 | 'CRITICAL': 'red,bg_white',
989 | }
990 | )
991 |
992 | console_handler.setFormatter(formatter)
993 | logger.addHandler(console_handler)
994 |
995 | if len(sys.argv) > 1 and sys.argv[1] == "setup":
996 | setup()
997 | else:
998 | run()
--------------------------------------------------------------------------------