diff --git a/README.md b/README.md index 323d5e0..f5968df 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,10 @@ A comprehensive solution for deploying Wallarm filtering nodes on virtual machin | | **Docker** | **Native** | |---|---|---| -| Runtime | Wallarm container on Docker engine | Wallarm NGINX module installed directly on the OS | -| Artifacts | Docker static binaries + Wallarm image (from Git repo or local) | Wallarm all-in-one installer (`meganode.wallarm.com`) | -| Multi-node on one host | ✅ Yes (unique ports) | ⚠️ One node per host (single system NGINX) | +| Runtime | Wallarm container on Docker engine | Wallarm Native Node (go-node, `connector-server` mode) installed directly on the OS | +| Artifacts | Docker static binaries + Wallarm image (from Git repo or local) | Wallarm all-in-one installer (`repo.wallarm.com`) | +| Multi-node on one host | ✅ Yes (unique ports) | ✅ Yes (per-node systemd template units) | +| Management | 4 scripts (`check`/`deploy`/`reconfigure`/`uninstall`) | 1 unified script (`wallarm-native.sh`) | | Directory | `docker/` | `native/` | | Requires Docker | ✅ (installed automatically) | ❌ Never installed | | Best for | LXC/containers, multiple nodes, air-gapped | Simple single VM, minimal footprint, no containers | @@ -17,11 +18,11 @@ A comprehensive solution for deploying Wallarm filtering nodes on virtual machin - **Automated Preflight Checks** – Validates system readiness, network connectivity, and resource availability (per deployment type) - **Smart Artifact Management** – Git Repositorys-first approach with local fallback support (Docker type) -- **Multiple Node Support (Docker)** – Deploy multiple Wallarm instances on the same VM with unique port configurations +- **Multiple Node Support** – Deploy multiple Wallarm instances on the same VM with unique port configurations (Docker) or per-node systemd units (Native) - **Interactive Configuration** – User-friendly prompts for cloud region, ports, token, and upstream applications - **Comprehensive Validation** – Network tests, port availability checks, and deployment verification -- **Persistence & Management** – Automatic service creation (systemd/OpenRC/SysV), start scripts, and health monitoring -- **Post‑Deployment Reconfiguration** – Easily update trusted proxy IPs and change operation mode without redeploying +- **Persistence & Management** – Automatic service creation and health monitoring (systemd/OpenRC/SysV for Docker; systemd template units for Native) +- **Post‑Deployment Reconfiguration** – Easily update trusted proxy IPs and change operation mode without redeploying (Docker) or node address/token/labels (Native) - **Clean Uninstallation** – Safe removal of containers, packages, and configuration files ## Prerequisites @@ -37,7 +38,7 @@ A comprehensive solution for deploying Wallarm filtering nodes on virtual machin - **Bash**: Version 4.0+ (included with most Linux distributions) - **curl** or **wget**: For downloading scripts and artifacts - **sudo**: For package installation and system configuration -- **systemd**, **OpenRC** or **sysvinit**: For service management +- **systemd**: Required for Native deployment (per-node template units); Docker also supports OpenRC/sysvinit ## Quick Start @@ -62,10 +63,6 @@ The setup script downloads the shared library and makes executable: - `docker/wallarm-ct-deploy.sh` – Main deployment script (Docker) - `docker/wallarm-ct-reconfigure.sh` – Modify configuration after deployment (Docker) - `docker/wallarm-ct-uninstall.sh` – Remove a Wallarm node (Docker) -- `native/wallarm-ct-check.sh` – Preflight validation (Native) -- `native/wallarm-ct-deploy.sh` – Main deployment script (Native) -- `native/wallarm-ct-reconfigure.sh` – Modify configuration after deployment (Native) -- `native/wallarm-ct-uninstall.sh` – Remove a Wallarm node (Native) - `native/wallarm-native.sh` – Unified single-script manager for the Wallarm Native Node (connector mode) ### 2. Run Preflight Check @@ -75,15 +72,14 @@ The setup script downloads the shared library and makes executable: ./docker/wallarm-ct-check.sh # Native deployment -./native/wallarm-ct-check.sh +sudo ./native/wallarm-native.sh --preflight ``` -The preflight check will: +The preflight checks will: - Verify system compatibility (OS, architecture, init system) -- Test network connectivity to Wallarm cloud endpoints +- Test network connectivity to Wallarm cloud endpoints and installers - Validate artifact availability (Docker: Git repo / local files; Native: all-in-one installer) -- Validate resource availability -- Generate a `.env` file with results +- Validate resource availability and listen-port availability ### 3. Deploy Wallarm Node @@ -91,15 +87,15 @@ The preflight check will: # Docker deployment sudo ./docker/wallarm-ct-deploy.sh -# Native deployment -sudo ./native/wallarm-ct-deploy.sh +# Native deployment (interactive, multi-node) +sudo ./native/wallarm-native.sh --install ``` The deployment script will: -1. Read preflight check results -2. Prompt for configuration (ports, upstream application, Wallarm token, trusted proxies) +1. Run preflight checks (Native) / read preflight results (Docker) +2. Prompt for configuration (Docker: ports, upstream, token, proxies; Native: node names, listen addresses, token) 3. **Docker**: Install Docker, download and load the Wallarm image, configure and start the container -4. **Native**: Download and run the Wallarm all-in-one installer, configure NGINX, reload and verify +4. **Native**: Download and run the Wallarm all-in-one installer, register nodes, start per-node systemd units 5. Verify deployment with health checks ## Required Information Before Deployment @@ -108,18 +104,19 @@ To ensure a smooth deployment, have the following information ready before start | Item | Description | Example | Notes | |------|-------------|---------|-------| -| **Inbound Port** | The port on which the Wallarm node will listen for incoming HTTP traffic. | `80` (HTTP) or `8080` | Must be unused on the server. If port 80 is already in use, choose another. | -| **Application Server (Upstream) IP/Hostname** | The IP address or hostname of the backend application that Wallarm will forward traffic to. | `192.168.1.100` or `app.internal.local` | Must be reachable from the Wallarm node. If the application runs on the same physical machine, do **not** use `127.0.0.1` – use the host's actual IP. | -| **Application Server Port** | The port on which the backend application listens. | `8080` | Must be open and listening. | -| **Wallarm Node Token** | A token obtained from the Wallarm Console when creating a new "Wallarm node". | `base64_encoded_string` | Copy it exactly. It will be pasted during the deployment process. | -| **Trusted Proxy IPs/CIDRs** (Optional) | The IP address(es) of any load balancers, firewalls, or CDNs that sit in front of the Wallarm node and set the `X-Real-IP` header. | `10.0.0.10` or `192.168.0.0/24` | If the node is directly accessible from the internet (no proxy in front), leave empty. Multiple entries can be space-separated. | -| **Wallarm Cloud Region** | Which Wallarm cloud to use – US or EU. | `US` or `EU` | The script will test connectivity to both and only show reachable ones. | -| **Operation Mode** (Optional, can be changed later) | The initial operation mode. `monitoring` only logs attacks, `block` actively blocks. | `monitoring` (recommended for first deployment) | The script defaults to `monitoring`. You can change it later using the reconfigure script. | +| **Inbound Port / Listen Address** | Docker: port the node listens on. Native: `IP:Port` connector address per node. | `80` or `0.0.0.0:8081` | Must be unused on the server. Native can run multiple nodes on different ports. | +| **Application Server (Upstream) IP/Hostname** (Docker) | The IP address or hostname of the backend application that Wallarm will forward traffic to. | `192.168.1.100` or `app.internal.local` | Must be reachable from the Wallarm node. Do **not** use `127.0.0.1` for a local app – use the host's actual IP. | +| **Application Server Port** (Docker) | The port on which the backend application listens. | `8080` | Must be open and listening. | +| **Wallarm Node Token** | A token obtained from the Wallarm Console when creating a new "Wallarm node". | `base64_encoded_string` | Copy it exactly. It will be pasted during the deployment process. Native requires a token with the Deploy role. | +| **Node Labels** (Native, optional) | Labels applied to the node (defaults to `group=`). | `group=prod` | Can be changed later via `--config --labels`. | +| **Trusted Proxy IPs/CIDRs** (Docker, optional) | IP(s) of load balancers/firewalls in front of the node that set the `X-Real-IP` header. | `10.0.0.10` or `192.168.0.0/24` | Leave empty if no proxy in front. Multiple entries space-separated. | +| **Wallarm Cloud Region** | Which Wallarm cloud to use – US or EU. | `US` or `EU` | Scripts test connectivity to both and only show reachable ones. | +| **Operation Mode** (Docker, optional) | Initial operation mode. `monitoring` logs attacks, `block` blocks. | `monitoring` | Defaults to `monitoring`; changeable later via the reconfigure script. | ### Additional Preparation Steps - **Ensure the backend application is running** and reachable from the Wallarm server. Test with `telnet `. -- **If you plan to use a custom domain**, be prepared to configure DNS to point to the server's public IP (or the load balancer) – the Wallarm node itself does not require a domain for basic setup. +- **If you plan to use a custom domain**, be prepared to configure DNS to point to the server's public IP (or the load balancer). - **If the server is behind a firewall**, open the inbound port (e.g., 80) to allow traffic from the internet or the load balancer. ## Detailed Usage @@ -136,7 +133,7 @@ Before deployment, you need a Wallarm Node Token from the Wallarm Console: - **Token Format**: Base64 encoded string (alphanumeric with `+`, `/`, `=`, `-`, `_`) - **Documentation**: [Official Wallarm Documentation](https://docs.wallarm.com/) -#### Header Configuration for Firewalls/Ingress Controllers +#### Header Configuration for Firewalls/Ingress Controllers (Docker) To ensure proper IP address detection and metadata forwarding, configure your firewall or ingress controller to include these headers: ```nginx @@ -146,7 +143,7 @@ proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; ``` -**Note**: The deployment scripts configure the first three headers automatically. You must manually add `X-Forwarded-Host: "$host"` to your existing firewall/ingress configuration. +**Note**: The Docker deployment script configures the first three headers automatically. You must manually add `X-Forwarded-Host: "$host"` to your existing firewall/ingress configuration. ## Docker Deployment (`docker/`) @@ -176,33 +173,16 @@ You can deploy multiple Wallarm nodes on the same virtual machine by: ## Native Deployment (`native/`) -The native deployment installs Wallarm directly on the operating system **without Docker**, using the official Wallarm **all-in-one installer**: - -- The installer is downloaded from `https://meganode.wallarm.com/` (version configurable via the `WALLARM_VERSION` environment variable, default `6.12.7`) -- It automatically detects your OS and NGINX version, adds the Wallarm repositories, installs `wallarm-node` + the NGINX dynamic module, and registers the node -- Node registration is performed by the installer itself in batch mode (using your Wallarm token) -- The node configuration is written to `/opt/wallarm/etc/wallarm/node.yaml` -- The system NGINX is configured with a `wallarm-.conf` server block in `/etc/nginx/conf.d/` - -**Notes on native deployment:** -- **One node per host**: native uses the system NGINX, so multiple Wallarm nodes on one host are not supported (unlike Docker). Use unique ingress ports only if you run a single node alongside other services. -- The deploy script keeps a copy of the generated NGINX config in `/opt/wallarm//nginx.conf` and a log of the `nginx -t` test. -- `curl http://127.0.0.8/wallarm-status` reports Wallarm module statistics after deployment. - -### Example: Version Pinning - -```bash -WALLARM_VERSION=6.12.7 sudo ./native/wallarm-ct-deploy.sh -``` +The native deployment installs the **Wallarm Native Node** (go-node, `connector-server` mode) directly on the operating system **without Docker**, using a single unified manager script. ### Unified Node Manager (`native/wallarm-native.sh`) -For the **Wallarm Native Node** product (go-node, `connector-server` mode, no NGINX module), the repository provides a unified single-script manager. It manages multiple isolated nodes under `/opt/wallarm/nodes/` via a systemd template unit (`wallarm-node@.service`): +`wallarm-native.sh` manages multiple isolated nodes under `/opt/wallarm/nodes/` via a systemd template unit (`wallarm-node@.service`): ```bash sudo ./native/wallarm-native.sh --preflight # preflight checks only sudo ./native/wallarm-native.sh --install # interactive multi-node install (parallel) -sudo ./native/wallarm-native.sh --config --node node1 --address 0.0.0.0:9090 +sudo ./native/wallarm-native.sh --config --node node1 --address 0.0.0.0:9090 [--token TOKEN] [--labels LABELS] sudo ./native/wallarm-native.sh --remove --node node2 sudo ./native/wallarm-native.sh --status [NODE] # node status (all or one) ``` @@ -212,39 +192,37 @@ Key characteristics: - Per-node isolated directories (`etc/`, `var/log/`, `var/run/`), with the Wallarm token stored in a `chmod 600` env file - All-in-one installer is downloaded from `https://repo.wallarm.com/linux/wallarm-native-node/latest/all-in-one/` (override with `WALLARM_INSTALLER_URL`, architecture with `WALLARM_INSTALLER_ARCH`) - Parallel installation with per-node install logs (`install.log`) +- Nodes are started automatically via systemd and restart on failure -> **Note:** This script targets the Wallarm **Native Node** (connector mode). The `native/wallarm-ct-*.sh` scripts target the **NGINX-module** native deployment. Both are no-Docker options; choose the one that matches your Wallarm product. +## Reconfiguration -## Reconfiguration Script (`wallarm-ct-reconfigure.sh`) - -After deployment, you may need to adjust: - -- **Trusted proxy IPs/CIDRs** – When the network topology changes (new load balancer, CDN, firewall) -- **Operation mode** – Switch from `monitoring` to `block` after verifying correct operation - -The reconfigure script safely modifies the configuration of an existing instance, creates a backup, and applies the changes (Docker: restarts the container; Native: tests and reloads NGINX). - -**Usage**: +### Docker +The reconfigure script safely modifies the configuration of an existing instance, creates a backup, and restarts the container: ```bash -# Docker sudo ./docker/wallarm-ct-reconfigure.sh +``` +It can update trusted proxy IPs/CIDRs and switch the operation mode (`monitoring` ↔ `block`). -# Native -sudo ./native/wallarm-ct-reconfigure.sh +### Native +Use the unified manager to update an existing node: +```bash +sudo ./native/wallarm-native.sh --config --node node1 --address 0.0.0.0:9090 +sudo ./native/wallarm-native.sh --config --node node1 --token +sudo ./native/wallarm-native.sh --config --node node1 --labels "group=prod" ``` -It will detect installed instances, show current settings, and guide you through the changes. - -## Uninstallation (`wallarm-ct-uninstall.sh`) - -To completely remove a Wallarm node: +## Uninstallation +### Docker ```bash -# Docker: remove container/image and optionally Docker +# Remove container/image and optionally Docker sudo ./docker/wallarm-ct-uninstall.sh +``` -# Native: remove NGINX config, Wallarm packages, and node data -sudo ./native/wallarm-ct-uninstall.sh +### Native +```bash +# Remove a single node (stops systemd unit, deletes its directory) +sudo ./native/wallarm-native.sh --remove --node node2 ``` ## Artifact Sources @@ -269,7 +247,7 @@ The Docker deployment uses a smart fallback approach for artifact retrieval: ### Native Deployment (Source) -The native deployment downloads the Wallarm **all-in-one installer** directly from `https://meganode.wallarm.com/`. No Docker artifacts are required. Current versions are listed at [node-artifact-versions](https://docs.wallarm.com/updating-migrating/node-artifact-versions/). +The native deployment downloads the Wallarm **all-in-one installer** directly from `https://repo.wallarm.com/linux/wallarm-native-node/latest/all-in-one/`. No Docker artifacts are required. Current versions are listed at [node-artifact-versions](https://docs.wallarm.com/updating-migrating/node-artifact-versions/). ## Suggested Resources @@ -306,26 +284,26 @@ The native deployment downloads the Wallarm **all-in-one installer** directly fr - Validation helpers (IP address, CIDR, port availability) - Artifact download and checksum verification -### `docker/wallarm-ct-check.sh` / `native/wallarm-ct-check.sh` -**Purpose**: System validation and preflight checks +### `docker/wallarm-ct-check.sh` +**Purpose**: System validation and preflight checks (Docker) **Key Functions**: - OS compatibility verification (Ubuntu, CentOS, Debian, Alpine) - Network connectivity testing (US/EU cloud endpoints) - Resource availability assessment -- Artifact source validation (Docker: binaries/images; Native: installer) +- Docker artifact source validation (Git repo / local binaries/images) - Environment file generation (`.env`) **Usage**: ```bash # Run check with default settings -.//wallarm-ct-check.sh +./docker/wallarm-ct-check.sh # Enable debug output -DEBUG=1 .//wallarm-ct-check.sh +DEBUG=1 ./docker/wallarm-ct-check.sh # Disable SSL certificate validation (for self-signed certs) -WALLARM_INSECURE_SSL=0 .//wallarm-ct-check.sh +WALLARM_INSECURE_SSL=0 ./docker/wallarm-ct-check.sh ``` ### `docker/wallarm-ct-deploy.sh` @@ -348,31 +326,37 @@ sudo ./docker/wallarm-ct-deploy.sh WALLARM_TOKEN="your_token_here" sudo ./docker/wallarm-ct-deploy.sh ``` -### `native/wallarm-ct-deploy.sh` -**Purpose**: Wallarm node deployment and configuration (Native, no Docker) +### `docker/wallarm-ct-reconfigure.sh` +**Purpose**: Modify configuration of an existing Docker Wallarm node **Key Functions**: -- Interactive configuration wizard -- Downloads and runs the Wallarm all-in-one installer (batch mode) -- Node registration with your Wallarm token -- NGINX server block configuration (proxy, wallarm_mode, trusted proxies, health endpoint) -- NGINX test + reload -- Health check and deployment verification +- Update `set_real_ip_from` (trusted proxy IPs/CIDRs) +- Change `wallarm_mode` (monitoring/block) +- Create backup of current configuration +- Restart container to apply changes **Usage**: ```bash -# Interactive deployment -sudo ./native/wallarm-ct-deploy.sh +sudo ./docker/wallarm-ct-reconfigure.sh +``` -# Pin a specific Wallarm version -WALLARM_VERSION=6.12.7 sudo ./native/wallarm-ct-deploy.sh +### `docker/wallarm-ct-uninstall.sh` +**Purpose**: Safe removal of Docker Wallarm nodes -# Add node labels (group) -WALLARM_LABELS='group=prod' sudo ./native/wallarm-ct-deploy.sh +**Key Functions**: +- Interactive confirmation with safety checks +- Container/image removal +- Docker cleanup (service files, binaries, config, group) +- Configuration directory removal + +**Usage**: +```bash +# Interactive uninstallation +sudo ./docker/wallarm-ct-uninstall.sh ``` ### `native/wallarm-native.sh` -**Purpose**: Unified single-script manager for the Wallarm Native Node (connector mode, no Docker/NGINX module) +**Purpose**: Unified single-script manager for the Wallarm Native Node (connector mode, no Docker) **Key Functions**: - Preflight checks (root, systemd, architecture, commands, connectivity, resources, ports) @@ -394,42 +378,13 @@ sudo ./native/wallarm-native.sh --remove --node node2 sudo ./native/wallarm-native.sh --status ``` -### `wallarm-ct-reconfigure.sh` -**Purpose**: Modify configuration of an existing Wallarm node - -**Key Functions**: -- Update `set_real_ip_from` (trusted proxy IPs/CIDRs) -- Change `wallarm_mode` (monitoring/block) -- Create backup of current configuration -- Apply changes (Docker: container restart; Native: NGINX reload) - -**Usage**: -```bash -sudo .//wallarm-ct-reconfigure.sh -``` - -### `wallarm-ct-uninstall.sh` -**Purpose**: Safe removal of Wallarm nodes - -**Key Functions**: -- Interactive confirmation with safety checks -- Docker: container/image removal, Docker cleanup; Native: NGINX config + package removal -- Configuration directory removal -- Optional artifact cleanup - -**Usage**: -```bash -# Interactive uninstallation -sudo .//wallarm-ct-uninstall.sh -``` - ## Troubleshooting ### Common Issues #### 1. Preflight Check Fails ```bash -# Check detailed errors +# Docker: check detailed errors cat .env # Verify network connectivity manually @@ -473,19 +428,18 @@ groups $USER docker run --rm hello-world ``` -#### 5. Native Installer Fails +#### 5. Native Installer / Node Fails ```bash -# The all-in-one installer logs its output to the terminal and to files # Check the current version at https://docs.wallarm.com/updating-migrating/node-artifact-versions/ +# Override the installer URL if needed: +WALLARM_INSTALLER_URL="" sudo ./native/wallarm-native.sh --install -# Verify node registration -ls -la /opt/wallarm/etc/wallarm/node.yaml - -# Check Wallarm module status -curl http://127.0.0.8/wallarm-status +# Check a node's install log and service status +sudo cat /opt/wallarm/nodes//install.log +sudo systemctl status wallarm-node@ --no-pager ``` -#### 6. Header Configuration Warnings +#### 6. Header Configuration Warnings (Docker) Ensure your upstream firewall/load balancer includes: - `X-Real-IP: "$remote_addr"` - `X-Forwarded-For: "$proxy_add_x_forwarded_for"` @@ -493,10 +447,10 @@ Ensure your upstream firewall/load balancer includes: - `X-Forwarded-Host: "$host"` ### Log Files -- **Preflight Check**: `~/logs/wallarm-check.log` (Docker) / `~/logs/wallarm-check-native.log` (Native) -- **Deployment**: `~/logs/wallarm-deployment.log` (Docker) / `~/logs/wallarm-deployment-native.log` (Native) +- **Docker Preflight Check**: `~/logs/wallarm-check.log` +- **Docker Deployment**: `~/logs/wallarm-deployment.log` - **Docker Container Logs**: `/opt/wallarm-/container.log` -- **NGINX Logs (Native)**: `/var/log/nginx/error.log` +- **Native Node Logs**: `/opt/wallarm/nodes//install.log` and `/opt/wallarm/nodes//var/log/` - **System Logs**: `/var/log/syslog` or `/var/log/messages` ## Security Considerations @@ -509,25 +463,26 @@ Ensure your upstream firewall/load balancer includes: ### Access Control - Restrict `sudo` access to deployment scripts - Use separate service accounts for Wallarm services -- Implement proper secret management for Wallarm tokens +- Implement proper secret management for Wallarm tokens (Native stores them in `chmod 600` env files) ### Monitoring & Auditing - Enable logging with rotation - Monitor resource usage -- Regular security updates for Docker/NGINX and host OS +- Regular security updates for Docker and host OS ## Maintenance ### Regular Tasks 1. **Log Rotation**: Configure logrotate for logs -2. **Updates**: Periodically update Docker engine/NGINX and Wallarm node +2. **Updates**: Periodically update Docker/NGINX and Wallarm node 3. **Image/Version Updates**: Check for new Wallarm node versions 4. **Backup**: Regular backup of configuration directories ### Version Updates -When updating Wallarm node version: -1. **Docker**: Pull new image from Git Repositorys or official registry, stop existing container, deploy new container with updated image, verify functionality before removing old container -2. **Native**: Set `WALLARM_VERSION` to the new version and re-run the deploy script, or follow the [official upgrade guide](https://docs.wallarm.com/updating-migrating/) +When updating the Wallarm Native Node version: +1. Check the latest version at [node-artifact-versions](https://docs.wallarm.com/updating-migrating/node-artifact-versions/) +2. Re-download via the latest all-in-one installer (or pin with `WALLARM_INSTALLER_URL`) +3. Remove and re-install the node, or follow the [official upgrade guide](https://docs.wallarm.com/updating-migrating/) ## Repository Structure @@ -546,10 +501,6 @@ wallarm/ │ ├── binaries/ # Docker static binaries │ └── images/ # Wallarm Docker images └── native/ # Native deployment (no Docker) - ├── wallarm-ct-check.sh - ├── wallarm-ct-deploy.sh - ├── wallarm-ct-reconfigure.sh - ├── wallarm-ct-uninstall.sh └── wallarm-native.sh # Unified single-script node manager (Native Node product) ``` diff --git a/changelog.md b/changelog.md index d769dea..76cd4fa 100644 --- a/changelog.md +++ b/changelog.md @@ -10,12 +10,7 @@ and this project adheres to date-based versioning (YYYY-MM.x). - **setup.sh interactive prompt broken under `curl ... | bash`**: the deployment-type prompt and overwrite confirmation read from stdin, which is the script pipe (not the terminal) when piped to bash — the prompt was silently skipped and only Docker scripts were downloaded. setup.sh is now **non-interactive by default and downloads BOTH deployment types** (`docker/` + `native/`), so the native option is always available. Use `DEPLOYMENT_TYPE=docker|native` to download only one type. ### Added -- **Native deployment type**: Wallarm filtering node can now be deployed directly on the OS **without Docker** - - `native/wallarm-ct-check.sh` – Preflight validation for native deployment (no Docker artifact checks) - - `native/wallarm-ct-deploy.sh` – Downloads and runs the official Wallarm all-in-one installer (`meganode.wallarm.com`, version configurable via `WALLARM_VERSION`), configures the NGINX server block, reloads and verifies the node - - `native/wallarm-ct-reconfigure.sh` – Update trusted proxies / `wallarm_mode` via NGINX test + reload - - `native/wallarm-ct-uninstall.sh` – Remove NGINX config, Wallarm packages/repos, and `/opt/wallarm` data -- **Unified node manager**: `native/wallarm-native.sh` – single-script manager for the Wallarm Native Node (go-node, connector-server mode) +- **Native deployment**: Wallarm filtering node can now be deployed directly on the OS **without Docker** via the unified manager `native/wallarm-native.sh` (Wallarm Native Node, go-node, `connector-server` mode) - `--preflight` checks (root, systemd, architecture, required commands, installer + Wallarm cloud connectivity, disk/memory, listen-port availability); auto-run before `--install` - Interactive parallel multi-node installation with per-node systemd template units (`wallarm-node@.service`) - `--config` (address/token/labels, safe env rewrite), `--remove`, `--status [NODE]` @@ -30,18 +25,18 @@ and this project adheres to date-based versioning (YYYY-MM.x). - **Repository structure** now separates deployment types: - `docker/` – all Docker-based scripts moved here (`git mv`, history preserved) - `docker/binaries/` and `docker/images/` – Docker artifacts moved into the Docker tree - - `native/` – new native (no-Docker) deployment scripts + - `native/` – native (no-Docker) deployment, containing only the unified `wallarm-native.sh` - `common/` – shared library +- **Removed** the `native/wallarm-ct-*.sh` scripts (NGINX-module based native deployment) so the native deployment is represented solely by the unified `wallarm-native.sh`; the `wallarm-ct-*` family is now Docker-only - **Artifact URLs** updated to the `docker/` prefix (`/docker/binaries/...`, `/docker/images/...`) - **Docker scripts** refactored to source `common/wallarm-lib.sh` (removed duplicated helper functions; behavior preserved) -- **setup.sh** downloads the shared library and scripts per deployment type into `docker/`/`native/` (native includes `wallarm-native.sh`); supports `DEPLOYMENT_TYPE=docker|native` to download only one type -- **README.md** rewritten to document both deployment types, the new structure, the unified manager, and native-specific usage +- **setup.sh** downloads the shared library and scripts per deployment type into `docker/`/`native/` (native = `wallarm-native.sh`); supports `DEPLOYMENT_TYPE=docker|native` to download only one type +- **README.md** rewritten to document both deployment types, the new structure, and the unified native manager ### Notes -- Native deployment supports one node per host (system NGINX); multi-node remains a Docker feature -- Native installer version defaults to `6.12.7` and can be pinned via `WALLARM_VERSION` +- The `wallarm-ct-*` script family is Docker-only; native deployment uses `wallarm-native.sh` +- Native multi-node is supported via per-node systemd template units - Docker deployment behavior is unchanged apart from the new directory layout -- The unified manager targets the Wallarm **Native Node** product; the `native/wallarm-ct-*.sh` scripts target the **NGINX-module** native deployment. Both are no-Docker options ## [2026-04.1] - 2026-04-21 ### Added diff --git a/native/wallarm-ct-check.sh b/native/wallarm-ct-check.sh deleted file mode 100755 index 548c0fd..0000000 --- a/native/wallarm-ct-check.sh +++ /dev/null @@ -1,364 +0,0 @@ -#!/bin/bash -# ============================================================================== -# WALLARM PREFLIGHT CHECK SCRIPT - V1.0 (Native deployment) -# ============================================================================== -# Purpose: Validate system readiness for native (no-Docker) Wallarm deployment -# Features: -# - Non-interactive system validation (sudo, OS, architecture, init system) -# - Network connectivity testing (US/EU cloud + Wallarm all-in-one installer) -# - Resource availability assessment -# - Outputs results to .env file for deployment script -# - DAU-friendly error messages with remediation -# ============================================================================== - -# Script location and shared library (colors, logging, validation, detection, connectivity) -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# shellcheck source=../common/wallarm-lib.sh -source "$SCRIPT_DIR/../common/wallarm-lib.sh" - -# Strict error handling -set -euo pipefail -trap early_error_handler ERR - -# Configuration -ENV_FILE=".env" -LOG_FILE="${HOME:-.}/logs/wallarm-check-native.log" - -# Native install artifacts (Wallarm all-in-one installer) -WALLARM_VERSION="${WALLARM_VERSION:-6.12.7}" -INSTALLER_BASE_URL="https://meganode.wallarm.com/${WALLARM_VERSION%.*}" -INSTALLER_NAME="wallarm-${WALLARM_VERSION}.x86_64-glibc.sh" -INSTALLER_URL="${INSTALLER_BASE_URL}/${INSTALLER_NAME}" - -# Cloud endpoints (from Wallarm documentation) -EU_DATA_NODES=("api.wallarm.com" "node-data0.eu1.wallarm.com" "node-data1.eu1.wallarm.com") -US_DATA_NODES=("us1.api.wallarm.com" "node-data0.us1.wallarm.com" "node-data1.us1.wallarm.com") - -# Global result tracking -CHECK_RESULT="pass" -CHECK_ERRORS=() -INSTALLER_REACHABLE="false" - -# ============================================================================== -# RESULT TRACKING & ENV FILE -# ============================================================================== - -add_error() { - local error_msg="$1" - CHECK_ERRORS+=("$error_msg") - CHECK_RESULT="fail" - log_message "ERROR" "$error_msg" -} - -write_env_file() { - local os_name="$1" - local os_version="$2" - local architecture="$3" - local init_system="$4" - local us_cloud_reachable="$5" - local eu_cloud_reachable="$6" - local installer_reachable="${7:-false}" - - cat > "$ENV_FILE" << EOF -# Wallarm Preflight Check Results (Native deployment) -# Generated: $(date '+%Y-%m-%d %H:%M:%S') -# Script: $0 - -result=$CHECK_RESULT -os_name=$os_name -os_version=$os_version -architecture=$architecture -init_system=$init_system -us_cloud_reachable=$us_cloud_reachable -eu_cloud_reachable=$eu_cloud_reachable -installer_reachable=$installer_reachable - -EOF - - if [ ${#CHECK_ERRORS[@]} -gt 0 ]; then - echo "# Errors:" >> "$ENV_FILE" - for i in "${!CHECK_ERRORS[@]}"; do - echo "error_$i=\"${CHECK_ERRORS[$i]}\"" >> "$ENV_FILE" - done - fi - - log_message "SUCCESS" "Check results written to $ENV_FILE" -} - -# ============================================================================== -# PRE-FLIGHT VALIDATION FUNCTIONS -# ============================================================================== - -validate_sudo_access() { - log_message "INFO" "Validating sudo access..." - - local os_name - os_name=$(uname -s | tr '[:upper:]' '[:lower:]') - - if ! command -v sudo >/dev/null 2>&1; then - add_error "sudo command not found" - return 1 - fi - - if [ "$os_name" = "darwin" ]; then - log_message "WARNING" "macOS detected: sudo authentication test skipped (may prompt during deployment)" - log_message "INFO" "Note: macOS is not a supported deployment target. This check is for Linux servers." - return 0 - fi - - if ! sudo -v; then - add_error "sudo authentication failed" - return 1 - fi - - log_message "SUCCESS" "Sudo access validated" - return 0 -} - -validate_required_commands() { - log_message "INFO" "Validating required system commands..." - - local missing_commands=() - - local os_name - os_name=$(uname -s | tr '[:upper:]' '[:lower:]') - - # Core commands required for native check and deployment scripts - local core_commands=( - "curl" # Required for downloading the all-in-one installer - "grep" # Used extensively - "cut" # Used for parsing output - "tr" # Used for text transformations - "sed" # Used for text processing - "head" # Used for limiting output - "tail" # Used for limiting output - "ls" # Used for file listing - "date" # Used for logging timestamps - "mkdir" # Used for creating directories - "chmod" # Used for permission changes - "tee" # Required for writing configuration files - "rm" # Required for cleanup operations - ) - - # Check each core command (command_exists comes from common library) - local cmd - for cmd in "${core_commands[@]}"; do - if ! command_exists "$cmd"; then - missing_commands+=("$cmd") - fi - done - - # Check for port checking utility (ss or netstat) - if [ "$os_name" != "darwin" ]; then - if ! command_exists ss && ! command_exists netstat; then - missing_commands+=("ss or netstat") - fi - fi - - # Detect init system and validate its control command - if [ "$os_name" != "darwin" ]; then - local init_system - init_system=$(detect_init_system) - - case "$init_system" in - "systemd") - if ! command_exists systemctl; then - missing_commands+=("systemctl") - fi - ;; - "openrc") - if ! command_exists rc-service; then - missing_commands+=("rc-service") - fi - ;; - "sysvinit") - if ! command_exists service; then - missing_commands+=("service") - fi - ;; - "upstart") - if ! command_exists initctl; then - missing_commands+=("initctl") - fi - ;; - *) - log_message "WARNING" "Unknown init system '$init_system', cannot validate init command" - ;; - esac - else - log_message "INFO" "Skipping init system validation on macOS (not a deployment target)" - fi - - if [ ${#missing_commands[@]} -gt 0 ]; then - local missing_list - missing_list=$(IFS=', '; echo "${missing_commands[*]}") - add_error "Missing required commands: $missing_list" - log_message "ERROR" "Please install missing commands and run the check again." - return 1 - fi - - log_message "SUCCESS" "All required system commands are available" - return 0 -} - -# ============================================================================== -# NETWORK CONNECTIVITY TESTING -# ============================================================================== - -perform_network_tests() { - log_message "INFO" "=== NETWORK CONNECTIVITY TESTING ===" - - # Test US cloud endpoints - local us_reachable - us_reachable=$(test_cloud_endpoints "US" "${US_DATA_NODES[@]}") - - # Test EU cloud endpoints - local eu_reachable - eu_reachable=$(test_cloud_endpoints "EU" "${EU_DATA_NODES[@]}") - - # Test Wallarm all-in-one installer reachability (needed for native install) - log_message "INFO" "Testing Wallarm all-in-one installer availability..." - if test_connectivity "$INSTALLER_URL" "Wallarm all-in-one installer"; then - INSTALLER_REACHABLE="true" - log_message "SUCCESS" "Wallarm installer is reachable (version $WALLARM_VERSION)" - else - log_message "WARNING" "Wallarm installer is not reachable at $INSTALLER_URL" - log_message "INFO" "Check https://docs.wallarm.com/updating-migrating/node-artifact-versions/ for the latest version." - fi - - echo "$us_reachable:$eu_reachable:$INSTALLER_REACHABLE" -} - -# ============================================================================== -# MAIN FUNCTION -# ============================================================================== - -main() { - clear - echo -e "${BLUE}${BOLD}" - echo "╔══════════════════════════════════════════════════════════════╗" - echo "║ WALLARM PREFLIGHT CHECK SCRIPT (Native) - V1.0 ║" - echo "║ System Readiness Validation for Deployment ║" - echo "╚══════════════════════════════════════════════════════════════╝${NC}" - echo -e "\n${YELLOW}Starting preflight check at: $(date)${NC}" - - # Initialize logging - local log_dir="${HOME:-.}/logs" - if [ ! -d "$log_dir" ]; then - if ! mkdir -p "$log_dir"; then - echo -e "${YELLOW}Cannot create log directory $log_dir, falling back to current directory...${NC}" - log_dir="." - fi - fi - - LOG_FILE="$log_dir/wallarm-check-native.log" - if ! : > "$LOG_FILE"; then - echo -e "${RED}Cannot create log file at $LOG_FILE${NC}" - echo -e "${YELLOW}Falling back to current directory...${NC}" - LOG_FILE="./wallarm-check-native.log" - : > "$LOG_FILE" 2>/dev/null || true - fi - if ! chmod 644 "$LOG_FILE" 2>/dev/null; then - echo -e "${YELLOW}Warning: Could not set permissions on log file${NC}" - fi - - log_message "INFO" "=== Wallarm Preflight Check (Native) Started ===" - - if [ "$INSECURE_SSL" = "1" ]; then - log_message "WARNING" "SSL certificate validation is DISABLED (insecure). Set WALLARM_INSECURE_SSL=0 to enable validation." - fi - - # Phase 1: System validation - log_message "INFO" "=== PHASE 1: SYSTEM VALIDATION ===" - - if ! validate_required_commands; then - add_error "Required system commands validation failed" - fi - - if ! validate_sudo_access; then - add_error "Sudo access validation failed" - fi - - local os_info - os_info=$(detect_os_and_version) - local os_name - os_name=$(echo "$os_info" | cut -d: -f1) - local os_version - os_version=$(echo "$os_info" | cut -d: -f2) - - local architecture - architecture=$(detect_architecture) - if [ "$architecture" = "unknown" ]; then - add_error "Unsupported architecture detected" - fi - - local init_system - init_system=$(detect_init_system) - - log_message "SUCCESS" "System validation completed:" - log_message "SUCCESS" " OS: $os_name $os_version" - log_message "SUCCESS" " Architecture: $architecture" - log_message "SUCCESS" " Init System: $init_system" - - # Phase 2: Network connectivity testing - log_message "INFO" "=== PHASE 2: NETWORK CONNECTIVITY TESTING ===" - - local network_results - network_results=$(perform_network_tests) - local us_reachable - us_reachable=$(echo "$network_results" | cut -d: -f1) - local eu_reachable - eu_reachable=$(echo "$network_results" | cut -d: -f2) - local installer_reachable - installer_reachable=$(echo "$network_results" | cut -d: -f3) - - log_message "SUCCESS" "Network testing completed:" - log_message "SUCCESS" " US Cloud Reachable: $us_reachable" - log_message "SUCCESS" " EU Cloud Reachable: $eu_reachable" - log_message "SUCCESS" " Wallarm Installer Reachable: $installer_reachable" - - # Phase 3: Write results - log_message "INFO" "=== PHASE 3: WRITING RESULTS ===" - - write_env_file "$os_name" "$os_version" "$architecture" "$init_system" \ - "$us_reachable" "$eu_reachable" "$installer_reachable" - - # Final summary - if [ "$CHECK_RESULT" = "pass" ]; then - log_message "SUCCESS" "=== PREFLIGHT CHECK PASSED ===" - echo -e "\n${GREEN}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}" - echo -e "${GREEN}${BOLD}║ PREFLIGHT CHECK PASSED - SYSTEM READY ║${NC}" - echo -e "${GREEN}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}" - echo -e "\n${CYAN}System is ready for native Wallarm deployment.${NC}" - echo -e "${YELLOW}Check results: $ENV_FILE${NC}" - echo -e "${YELLOW}Full log: $LOG_FILE${NC}" - echo -e "\n${GREEN}Next step: Run ./native/wallarm-ct-deploy.sh to proceed with deployment${NC}" - exit 0 - else - log_message "ERROR" "=== PREFLIGHT CHECK FAILED ===" - echo -e "\n${RED}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}" - echo -e "${RED}${BOLD}║ PREFLIGHT CHECK FAILED - SYSTEM NOT READY ║${NC}" - echo -e "${RED}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}" - echo -e "\n${YELLOW}${BOLD}Issues found:${NC}" - for error in "${CHECK_ERRORS[@]}"; do - echo -e " ${RED}•${NC} $error" - done - echo -e "\n${YELLOW}Check results: $ENV_FILE${NC}" - echo -e "${YELLOW}Full log: $LOG_FILE${NC}" - echo -e "\n${CYAN}Please fix the issues above and run the check again.${NC}" - exit 1 - fi -} - -# ============================================================================== -# SCRIPT EXECUTION -# ============================================================================== - -# Ensure we're in bash -if [ -z "$BASH_VERSION" ]; then - echo "Error: This script must be run with bash" >&2 - exit 1 -fi - -# Run main function -main "$@" diff --git a/native/wallarm-ct-deploy.sh b/native/wallarm-ct-deploy.sh deleted file mode 100755 index cac81ff..0000000 --- a/native/wallarm-ct-deploy.sh +++ /dev/null @@ -1,673 +0,0 @@ -#!/bin/bash -# ============================================================================== -# WALLARM DEPLOYMENT SCRIPT - V1.0 (Native deployment) -# ============================================================================== -# Purpose: Deploy Wallarm filtering node natively (NO Docker) after preflight -# Features: -# - Reads preflight check results from .env file -# - Interactive configuration (cloud region, ports, token, upstream) -# - Downloads and runs the official Wallarm all-in-one installer (meganode.wallarm.com) -# - Configures NGINX server block (proxy, wallarm_mode, trusted proxies, health) -# - Deployment verification (health endpoint, wallarm-status, node registration) -# - DAU-friendly error handling with remediation -# ============================================================================== - -# Script location and shared library (colors, logging, validation, detection, connectivity) -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# shellcheck source=../common/wallarm-lib.sh -source "$SCRIPT_DIR/../common/wallarm-lib.sh" - -# Strict error handling -set -euo pipefail -trap early_error_handler ERR - -# Configuration -ENV_FILE=".env" -LOG_FILE="${HOME:-.}/logs/wallarm-deployment-native.log" - -# Wallarm all-in-one installer (current recommended native install method) -# Override WALLARM_VERSION to pin a different version. -WALLARM_VERSION="${WALLARM_VERSION:-6.12.7}" -INSTALLER_BASE_URL="https://meganode.wallarm.com/${WALLARM_VERSION%.*}" - -# Optional node labels for the installer (e.g. 'group=prod') -WALLARM_LABELS="${WALLARM_LABELS:-}" - -# Deployment variables (set during execution) -CLOUD_REGION="" -API_HOST="" -INGRESS_PORT="" -UPSTREAM_IP="" -UPSTREAM_PORT="" -WALLARM_TOKEN="" -INSTANCE_NAME="" -INSTANCE_DIR="" -NGINX_CONFIG="" - -# Resource reachability from check script -US_CLOUD_REACHABLE="false" -EU_CLOUD_REACHABLE="false" -INSTALLER_REACHABLE="false" - -# ============================================================================== -# PREFLIGHT CHECK VERIFICATION -# ============================================================================== - -verify_preflight_check() { - log_message "INFO" "Verifying preflight check results..." - - if [ ! -f "$ENV_FILE" ]; then - log_message "ERROR" "Preflight check file not found: $ENV_FILE" - echo -e "\n${YELLOW}Preflight check has not been run or .env file is missing.${NC}" - echo -e "${YELLOW}Would you like to run the preflight check now?${NC}" - read -r -p "$(echo -e "${YELLOW}Run preflight check? (Y/n): ${NC}")" -n 1 - echo - if [[ ! $REPLY =~ ^[Nn]$ ]]; then - echo -e "${CYAN}Running preflight check...${NC}" - if ! "$SCRIPT_DIR/wallarm-ct-check.sh"; then - fail_with_remediation "Preflight check failed" \ - "Run the preflight check manually and fix any issues: -1. $SCRIPT_DIR/wallarm-ct-check.sh -2. Review the errors in $ENV_FILE -3. Fix the issues and run this script again" - fi - else - fail_with_remediation "Preflight check required" \ - "Run the preflight check before deployment: -1. $SCRIPT_DIR/wallarm-ct-check.sh -2. Review results in $ENV_FILE -3. Run this script again" - fi - fi - - # Load environment variables from .env file (from shared library) - if ! load_env_file "$ENV_FILE"; then - fail_with_remediation "Cannot load preflight results" \ - "The preflight check results file could not be read. -1. Run the preflight check: $SCRIPT_DIR/wallarm-ct-check.sh -2. Verify $ENV_FILE exists and is readable -3. Run this script again" - fi - - if [ "${CHECK_RESULT:-}" != "pass" ]; then - log_message "ERROR" "Preflight check failed (result: $CHECK_RESULT)" - echo -e "\n${YELLOW}Preflight check found issues. Please review:${NC}" - echo -e "${YELLOW}1. Check file: $ENV_FILE${NC}" - echo -e "${YELLOW}2. Run: $SCRIPT_DIR/wallarm-ct-check.sh${NC}" - echo -e "${YELLOW}3. Fix the issues and try again${NC}" - exit 1 - fi - - log_message "SUCCESS" "Preflight check verified:" - log_message "SUCCESS" " OS: $OS_NAME $OS_VERSION" - log_message "SUCCESS" " Architecture: $ARCHITECTURE" - log_message "SUCCESS" " Init System: $INIT_SYSTEM" - log_message "SUCCESS" " US Cloud Reachable: $US_CLOUD_REACHABLE" - log_message "SUCCESS" " EU Cloud Reachable: $EU_CLOUD_REACHABLE" - log_message "SUCCESS" " Wallarm Installer Reachable: $INSTALLER_REACHABLE" - - # Validate we have at least one cloud region reachable - if [ "$US_CLOUD_REACHABLE" = "false" ] && [ "$EU_CLOUD_REACHABLE" = "false" ]; then - fail_with_remediation "No Wallarm cloud region reachable" \ - "Network connectivity issues detected: -1. Check firewall rules for Wallarm cloud endpoints -2. Verify network connectivity -3. Run preflight check again: $SCRIPT_DIR/wallarm-ct-check.sh" - fi - - # The all-in-one installer must be reachable for a native deployment - if [ "$INSTALLER_REACHABLE" != "true" ]; then - fail_with_remediation "Wallarm all-in-one installer not reachable" \ - "Native deployment requires access to the Wallarm all-in-one installer: -1. Verify network access to $INSTALLER_BASE_URL -2. Check the current version at https://docs.wallarm.com/updating-migrating/node-artifact-versions/ -3. Pin the version with: WALLARM_VERSION= sudo ./$0" - fi -} - -# ============================================================================== -# CONFIGURATION COLLECTION -# ============================================================================== -# select_cloud_region, validate_ip_address and check_port_available are provided -# by the shared library (../common/wallarm-lib.sh). - -collect_configuration() { - log_message "INFO" "Collecting deployment configuration..." - - # Get ingress port - local default_port=80 - local ingress_port="" - while [[ ! "$ingress_port" =~ ^[0-9]+$ ]] || [ "$ingress_port" -lt 1 ] || [ "$ingress_port" -gt 65535 ]; do - read -r -p "$(echo -e "${YELLOW}Enter inbound port [${default_port}]: ${NC}")" ingress_port - ingress_port="${ingress_port:-$default_port}" - - if [[ ! "$ingress_port" =~ ^[0-9]+$ ]]; then - echo -e "${RED}Port must be a number${NC}" - elif [ "$ingress_port" -lt 1 ] || [ "$ingress_port" -gt 65535 ]; then - echo -e "${RED}Port must be between 1 and 65535${NC}" - elif ! check_port_available "$ingress_port"; then - echo -e "${RED}Port $ingress_port is already in use${NC}" - ingress_port="" - fi - done - - # Get application server details - local upstream_ip="" - local upstream_port="" - - echo -e "\n${CYAN}${BOLD}Application Server Configuration:${NC}" - echo -e "${YELLOW}Enter the IP/hostname and port of your backend application${NC}" - - while [[ -z "$upstream_ip" ]]; do - read -r -p "$(echo -e "${YELLOW}Upstream App IP/Hostname [127.0.0.1]: ${NC}")" upstream_ip - upstream_ip="${upstream_ip:-127.0.0.1}" - - if ! validate_ip_address "$upstream_ip" && \ - ! [[ "$upstream_ip" =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]*[a-zA-Z0-9]$ ]]; then - echo -e "${RED}Invalid IP/hostname format${NC}" - upstream_ip="" - fi - done - - while [[ ! "$upstream_port" =~ ^[0-9]+$ ]] || [ "$upstream_port" -lt 1 ] || [ "$upstream_port" -gt 65535 ]; do - read -r -p "$(echo -e "${YELLOW}Upstream App Port [8080]: ${NC}")" upstream_port - upstream_port="${upstream_port:-8080}" - - if [[ ! "$upstream_port" =~ ^[0-9]+$ ]]; then - echo -e "${RED}Port must be a number${NC}" - elif [ "$upstream_port" -lt 1 ] || [ "$upstream_port" -gt 65535 ]; then - echo -e "${RED}Port must be between 1 and 65535${NC}" - fi - done - - # Verify application server reachability - log_message "INFO" "Verifying application server reachability..." - if timeout 5 bash -c "cat < /dev/null > /dev/tcp/$upstream_ip/$upstream_port" 2>/dev/null; then - log_message "SUCCESS" "Application server $upstream_ip:$upstream_port is reachable" - else - log_message "WARNING" "Application server $upstream_ip:$upstream_port is not reachable" - echo -e "${YELLOW}${BOLD}Warning:${NC} Cannot reach application server at $upstream_ip:$upstream_port" - echo -e "${YELLOW}This may cause the Wallarm node to fail. Possible reasons:${NC}" - echo -e "1. Application server is not running" - echo -e "2. Firewall blocking port $upstream_port" - echo -e "3. Wrong IP/hostname" - echo -e "4. Application server not listening on that port" - - read -r -p "$(echo -e "${YELLOW}Continue anyway? (y/N): ${NC}")" -n 1 - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - fail_with_remediation "Application server unreachable" \ - "Ensure your application server is accessible: -1. Start your application server -2. Check it's listening: sudo ss -tlnp | grep :$upstream_port -3. Verify firewall rules allow inbound connections -4. Test connectivity: telnet $upstream_ip $upstream_port -5. If using hostname, verify DNS resolution: nslookup $upstream_ip" - fi - fi - - # Get Wallarm node token - local wallarm_token="" - echo -e "\n${CYAN}${BOLD}Wallarm Node Token:${NC}" - echo -e "${YELLOW}Get your token from Wallarm Console:${NC}" - echo -e "Create a new 'Wallarm node' and copy the token (will be visible as you type)" - while [[ -z "$wallarm_token" ]]; do - read -r -p "$(echo -e "${YELLOW}Paste Wallarm Node Token: ${NC}")" wallarm_token - wallarm_token=$(echo "$wallarm_token" | tr -d '[:space:]') - - if [[ -z "$wallarm_token" ]]; then - echo -e "${RED}Token cannot be empty${NC}" - elif [[ ! "$wallarm_token" =~ ^[A-Za-z0-9_+/=\-]+$ ]]; then - echo -e "${RED}Token contains invalid characters. Wallarm tokens are base64 strings (A-Z, a-z, 0-9, _, -, +, /, =)${NC}" - echo -e "${YELLOW}First 20 chars of what you entered: '${wallarm_token:0:20}...'${NC}" - wallarm_token="" - else - token_length=${#wallarm_token} - echo -e "${GREEN}Token accepted (${token_length} characters).${NC}" - echo -e "${YELLOW}First 8 chars for verification: ${wallarm_token:0:8}...${NC}" - fi - done - - # Get trusted proxy IPs for real IP configuration - local trusted_proxies="" - echo -e "\n${CYAN}${BOLD}Real Client IP Configuration:${NC}" - echo -e "${YELLOW}For Wallarm to see the real client IP, specify the IP address(es) of trusted proxies" - echo -e "(e.g., load balancers, firewalls, CDNs) that forward traffic to this node.${NC}" - echo -e "${YELLOW}You can enter:${NC}" - echo -e " - Single IP: 10.0.0.10" - echo -e " - CIDR range: 10.0.0.0/24" - echo -e " - Multiple entries separated by spaces: 10.0.0.10 10.0.1.0/24 192.168.1.1" - echo -e "${YELLOW}If unsure, you can leave empty and configure later${NC}" - - read -r -p "$(echo -e "${YELLOW}Trusted proxy IPs/CIDRs (space-separated): ${NC}")" trusted_proxies_input - - local validated_proxies=() - if [[ -n "$trusted_proxies_input" ]]; then - IFS=' ' read -ra proxy_array <<< "$trusted_proxies_input" - - for proxy in "${proxy_array[@]}"; do - proxy=$(echo "$proxy" | xargs) - if [[ -n "$proxy" ]]; then - if validate_ip_or_cidr "$proxy"; then - validated_proxies+=("$proxy") - else - echo -e "${RED}Invalid IP/CIDR format: $proxy${NC}" - echo -e "${YELLOW}Example valid formats: 10.0.0.10, 10.0.0.0/24, 192.168.1.1${NC}" - fi - fi - done - - if [[ ${#validated_proxies[@]} -eq 0 ]]; then - echo -e "${YELLOW}No valid proxy IPs provided. Will skip set_real_ip_from configuration.${NC}" - echo -e "${YELLOW}You can configure it later with the reconfigure script.${NC}" - trusted_proxies="" - else - trusted_proxies="${validated_proxies[*]}" - echo -e "${GREEN}Trusted proxies configured: $trusted_proxies${NC}" - fi - else - echo -e "${YELLOW}No trusted proxies specified. The node will see the last hop IP only.${NC}" - fi - - # Generate instance name and directory - local instance_name - instance_name="wallarm-$(hostname -s | tr '[:upper:]' '[:lower:]')-$(date +%Y%m%d)" - local instance_dir="/opt/wallarm/$instance_name" - - sudo mkdir -p "$instance_dir" - - log_message "SUCCESS" "Configuration collected:" - log_message "SUCCESS" " Ingress Port: $ingress_port" - log_message "SUCCESS" " Upstream: $upstream_ip:$upstream_port" - if [[ -n "$trusted_proxies" ]]; then - log_message "SUCCESS" " Trusted Proxies: $trusted_proxies" - else - log_message "INFO" " Trusted Proxies: Not configured (will need manual setup)" - fi - log_message "SUCCESS" " Instance: $instance_name" - log_message "SUCCESS" " Directory: $instance_dir" - - INGRESS_PORT="$ingress_port" - UPSTREAM_IP="$upstream_ip" - UPSTREAM_PORT="$upstream_port" - WALLARM_TOKEN="$wallarm_token" - INSTANCE_NAME="$instance_name" - INSTANCE_DIR="$instance_dir" - TRUSTED_PROXIES="$trusted_proxies" -} - -# ============================================================================== -# WALLARM NATIVE INSTALLATION (all-in-one installer) -# ============================================================================== - -install_wallarm_native() { - log_message "INFO" "Installing Wallarm filtering node natively (all-in-one installer)..." - - # Select the correct installer for the detected architecture - local arch_suffix - case "$ARCHITECTURE" in - "x86_64") arch_suffix="x86_64-glibc" ;; - "aarch64") arch_suffix="aarch64-glibc" ;; - *) - fail_with_remediation "Unsupported architecture for native install: $ARCHITECTURE" \ - "The Wallarm all-in-one installer supports x86_64 and aarch64. -1. Check architecture: uname -m -2. If you are on a 32-bit system, consider the Docker deployment instead. -3. See https://docs.wallarm.com/installation/nginx/all-in-one/ for supported platforms." - ;; - esac - - local installer_name="wallarm-${WALLARM_VERSION}.${arch_suffix}.sh" - local installer_url="${INSTALLER_BASE_URL}/${installer_name}" - - log_message "INFO" "Downloading Wallarm installer: $installer_name" - if ! download_from_git "$installer_url" "$installer_name" "Wallarm all-in-one installer"; then - fail_with_remediation "Failed to download Wallarm installer" \ - "Could not download $installer_url -1. Verify network access to meganode.wallarm.com -2. Check the current version at https://docs.wallarm.com/updating-migrating/node-artifact-versions/ -3. Pin the version with: WALLARM_VERSION= sudo ./$0" - fi - - chmod +x "$installer_name" - - # Build installer arguments (batch mode) - local install_args="-- --batch -t $WALLARM_TOKEN" - if [ "$CLOUD_REGION" = "US" ]; then - install_args="$install_args -c US" - log_message "INFO" "Using US cloud (us1.api.wallarm.com)" - else - log_message "INFO" "Using EU cloud (api.wallarm.com)" - fi - - # Run the installer (batch mode). The installer registers the node with the - # token and configures NGINX + the Wallarm module automatically. - log_message "INFO" "Running Wallarm all-in-one installer (this may take several minutes)..." - if [ -n "$WALLARM_LABELS" ]; then - log_message "INFO" "Using node labels: $WALLARM_LABELS" - if ! sudo env WALLARM_LABELS="$WALLARM_LABELS" sh "$installer_name" $install_args; then - rm -f "$installer_name" - fail_with_remediation "Wallarm installer failed" \ - "The all-in-one installer exited with an error. Check: -1. The installer log output above for the exact error -2. Token validity in the Wallarm Console -3. Network access to Wallarm repositories (the installer adds them automatically) -4. Disk space and memory: df -h / && free -h -5. Retry with a higher log verbosity, or see https://docs.wallarm.com/installation/nginx/all-in-one/" - fi - else - if ! sudo sh "$installer_name" $install_args; then - rm -f "$installer_name" - fail_with_remediation "Wallarm installer failed" \ - "The all-in-one installer exited with an error. Check: -1. The installer log output above for the exact error -2. Token validity in the Wallarm Console -3. Network access to Wallarm repositories (the installer adds them automatically) -4. Disk space and memory: df -h / && free -h -5. Retry with a higher log verbosity, or see https://docs.wallarm.com/installation/nginx/all-in-one/" - fi - fi - - rm -f "$installer_name" - log_message "SUCCESS" "Wallarm all-in-one installer completed" - - # Verify the node was registered - if [ -f "/opt/wallarm/etc/wallarm/node.yaml" ]; then - log_message "SUCCESS" "Wallarm node configuration found: /opt/wallarm/etc/wallarm/node.yaml" - else - log_message "WARNING" "Wallarm node configuration not found at /opt/wallarm/etc/wallarm/node.yaml" - echo -e "${YELLOW}The node may not have been registered. Check the installer output.${NC}" - fi -} - -# ============================================================================== -# NGINX CONFIGURATION -# ============================================================================== - -# Detect existing NGINX server blocks that would conflict with our ingress port -# and disable the default site if necessary. -resolve_port_conflict() { - local port="$1" - - log_message "INFO" "Checking for NGINX config conflicts on port $port..." - - # Only relevant for default port 80 where distro default sites listen - if [ "$port" != "80" ]; then - return 0 - fi - - # Look for default server blocks listening on port 80 - local conflicting - conflicting=$(grep -rl "listen.*80" /etc/nginx/sites-enabled/ /etc/nginx/conf.d/ 2>/dev/null | head -1 || true) - - if [ -n "$conflicting" ]; then - log_message "WARNING" "Default NGINX site found: $conflicting" - echo -e "${YELLOW}The default site listens on port 80 and may conflict with the Wallarm node.${NC}" - read -r -p "$(echo -e "${YELLOW}Disable it (backup to .bak)? (Y/n): ${NC}")" -n 1 - echo - if [[ ! $REPLY =~ ^[Nn]$ ]]; then - sudo mv "$conflicting" "${conflicting}.bak" - log_message "SUCCESS" "Disabled $conflicting (backup: ${conflicting}.bak)" - else - log_message "WARNING" "Keeping default site. The Wallarm node may not receive traffic on port 80." - fi - fi -} - -create_nginx_config() { - NGINX_CONFIG="/etc/nginx/conf.d/wallarm-${INSTANCE_NAME}.conf" - - log_message "INFO" "Creating NGINX configuration: $NGINX_CONFIG" - - # Also keep a copy in the instance directory for reference/backup - sudo tee "$NGINX_CONFIG" > /dev/null < /dev/null < /dev/null < /dev/null <&1 | tee "$INSTANCE_DIR/nginx-test.log"; then - fail_with_remediation "NGINX configuration test failed" \ - "NGINX rejected the configuration. Check the test output above. -1. Review the generated config: $NGINX_CONFIG -2. Look for port conflicts or syntax errors -3. Restore the backup if the default site was disabled -4. Manual test: sudo nginx -t" - fi - - # Reload according to init system - case "${INIT_SYSTEM:-systemd}" in - "systemd") - sudo systemctl reload nginx 2>/dev/null || sudo systemctl restart nginx - ;; - "openrc") - sudo rc-service nginx reload 2>/dev/null || sudo rc-service nginx restart - ;; - "sysvinit") - sudo service nginx reload 2>/dev/null || sudo service nginx restart - ;; - *) - sudo nginx -s reload 2>/dev/null || true - ;; - esac - - log_message "SUCCESS" "NGINX reloaded with Wallarm configuration" -} - -# ============================================================================== -# DEPLOYMENT VERIFICATION -# ============================================================================== - -verify_deployment() { - log_message "INFO" "Verifying native Wallarm deployment..." - - # Test ingress port - log_message "INFO" "Testing ingress port $INGRESS_PORT..." - if ! check_port_available "$INGRESS_PORT"; then - log_message "SUCCESS" "Ingress port $INGRESS_PORT is in use (as expected)" - else - log_message "WARNING" "Ingress port $INGRESS_PORT appears available (NGINX may not be listening)" - fi - - # Test health check endpoint - log_message "INFO" "Testing health check endpoint..." - local health_check_url="http://localhost:$INGRESS_PORT/health" - if curl -sf --connect-timeout 5 "$health_check_url" >/dev/null 2>&1; then - log_message "SUCCESS" "Health check endpoint responsive" - else - log_message "WARNING" "Health check endpoint not responsive (may need time to start)" - sleep 5 - if curl -sf --connect-timeout 5 "$health_check_url" >/dev/null 2>&1; then - log_message "SUCCESS" "Health check endpoint now responsive" - else - log_message "WARNING" "Health check endpoint still not responsive (check nginx config)" - fi - fi - - # Test handshake through filtering node - log_message "INFO" "Testing handshake through filtering node to upstream..." - local test_url="http://localhost:$INGRESS_PORT/" - if curl -sfI --connect-timeout 10 "$test_url" >/dev/null 2>&1; then - log_message "SUCCESS" "Handshake successful: filtering node can reach upstream" - else - log_message "WARNING" "Handshake failed (upstream may not be responding)" - log_message "INFO" "Checking if upstream is directly reachable..." - if timeout 5 bash -c "cat < /dev/null > /dev/tcp/$UPSTREAM_IP/$UPSTREAM_PORT" 2>/dev/null; then - log_message "ERROR" "Upstream is reachable but filtering node cannot proxy" - echo -e "${YELLOW}Possible NGINX configuration issue. Check:${NC}" - echo -e "1. NGINX error log: sudo tail -50 /var/log/nginx/error.log" - echo -e "2. NGINX config: $NGINX_CONFIG" - else - log_message "WARNING" "Upstream server is not reachable (as previously warned)" - fi - fi - - # Check Wallarm module status endpoint - log_message "INFO" "Checking Wallarm module status..." - if curl -sf --connect-timeout 5 "http://127.0.0.8/wallarm-status" >/dev/null 2>&1; then - log_message "SUCCESS" "Wallarm module is active (wallarm-status responsive)" - else - log_message "WARNING" "wallarm-status not responsive (module may need more time or a restart)" - fi - - # Check node registration file - if [ -f "/opt/wallarm/etc/wallarm/node.yaml" ]; then - log_message "SUCCESS" "Node is registered (node.yaml present)" - else - log_message "WARNING" "node.yaml not found - node may not be registered with the cloud" - fi - - log_message "SUCCESS" "Deployment verification completed" - echo -e "\n${GREEN}${BOLD}Verification Summary:${NC}" - echo -e " ${GREEN}✓${NC} NGINX + Wallarm module installed" - echo -e " ${GREEN}✓${NC} Ingress port: $INGRESS_PORT" - echo -e " ${GREEN}✓${NC} Upstream: $UPSTREAM_IP:$UPSTREAM_PORT" - echo -e " ${GREEN}✓${NC} Cloud region: $CLOUD_REGION ($API_HOST)" -} - -# ============================================================================== -# MAIN FUNCTION -# ============================================================================== - -main() { - clear - echo -e "${BLUE}${BOLD}" - echo "╔══════════════════════════════════════════════════════════════╗" - echo "║ WALLARM DEPLOYMENT SCRIPT (Native) - V1.0 ║" - echo "║ Filtering Node Deployment Without Docker ║" - echo "╚══════════════════════════════════════════════════════════════╝${NC}" - echo -e "\n${YELLOW}Starting deployment at: $(date)${NC}" - - # Initialize logging - local log_dir="${HOME:-.}/logs" - if [ ! -d "$log_dir" ]; then - if ! mkdir -p "$log_dir"; then - echo -e "${YELLOW}Cannot create log directory $log_dir, falling back to current directory...${NC}" - log_dir="." - fi - fi - - LOG_FILE="$log_dir/wallarm-deployment-native.log" - if ! : > "$LOG_FILE"; then - echo -e "${RED}Cannot create log file at $LOG_FILE${NC}" - echo -e "${YELLOW}Falling back to current directory...${NC}" - LOG_FILE="./wallarm-deployment-native.log" - : > "$LOG_FILE" 2>/dev/null || true - fi - if ! chmod 644 "$LOG_FILE" 2>/dev/null; then - echo -e "${YELLOW}Warning: Could not set permissions on log file${NC}" - fi - - log_message "INFO" "=== Wallarm Native Deployment Started ===" - - if [ "$INSECURE_SSL" = "1" ]; then - log_message "WARNING" "SSL certificate validation is DISABLED (insecure). Set WALLARM_INSECURE_SSL=0 to enable validation." - fi - - # Phase 1: Verify preflight check - log_message "INFO" "=== PHASE 1: PREFLIGHT CHECK VERIFICATION ===" - verify_preflight_check - - # Phase 2: Configuration collection - log_message "INFO" "=== PHASE 2: CONFIGURATION COLLECTION ===" - select_cloud_region - collect_configuration - - # Phase 3: Native installation (all-in-one installer) - log_message "INFO" "=== PHASE 3: WALLARM NATIVE INSTALLATION ===" - install_wallarm_native - - # Phase 4: NGINX configuration - log_message "INFO" "=== PHASE 4: NGINX CONFIGURATION ===" - resolve_port_conflict "$INGRESS_PORT" - create_nginx_config - reload_nginx - - # Phase 5: Verification - log_message "INFO" "=== PHASE 5: VERIFICATION ===" - verify_deployment - - # Success message - log_message "SUCCESS" "=== WALLARM NATIVE DEPLOYMENT COMPLETED SUCCESSFULLY ===" - echo -e "\n${GREEN}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}" - echo -e "${GREEN}${BOLD}║ WALLARM FILTERING NODE DEPLOYMENT SUCCESSFUL ║${NC}" - echo -e "${GREEN}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}" - echo -e "\n${CYAN}The Wallarm filtering node is now active and protecting your application.${NC}" - echo -e "${YELLOW}Full deployment log: $LOG_FILE${NC}" - echo -e "${YELLOW}Instance directory: $INSTANCE_DIR${NC}" - echo -e "\n${GREEN}To stop the node:${NC} sudo systemctl stop nginx" - echo -e "${GREEN}To restart:${NC} sudo systemctl restart nginx" - echo -e "${GREEN}To view logs:${NC} sudo tail -f /var/log/nginx/error.log" - echo -e "${GREEN}Node status:${NC} curl http://127.0.0.8/wallarm-status" - echo -e "\n${MAGENTA}${BOLD}Deployment completed successfully!${NC}" - echo -e "\n${YELLOW}Important next steps:${NC}" - echo -e "1. Monitor sync status in Wallarm Console" - echo -e "2. Test attack detection with safe test: curl http://localhost:$INGRESS_PORT/?wallarm_test=1" - echo -e "3. Review logs periodically: sudo tail -50 /var/log/nginx/error.log" - echo -e "4. Switch to block mode after validation: sudo ./native/wallarm-ct-reconfigure.sh" -} - -# ============================================================================== -# SCRIPT EXECUTION -# ============================================================================== - -# Ensure we're in bash -if [ -z "$BASH_VERSION" ]; then - echo "Error: This script must be run with bash" >&2 - exit 1 -fi - -# Run main function -main "$@" diff --git a/native/wallarm-ct-reconfigure.sh b/native/wallarm-ct-reconfigure.sh deleted file mode 100755 index 5a916fc..0000000 --- a/native/wallarm-ct-reconfigure.sh +++ /dev/null @@ -1,227 +0,0 @@ -#!/bin/bash -# ============================================================================== -# WALLARM RECONFIGURATION SCRIPT - V1.0 (Native deployment) -# ============================================================================== -# Purpose: Modify NGINX configuration of an existing native Wallarm node -# Features: -# - Update set_real_ip_from (trusted proxy IPs/CIDRs) -# - Change wallarm_mode (monitoring/block) -# - Backup current config before changes -# - NGINX test + reload instead of container restart -# - Interactive prompts with validation -# ============================================================================== - -# Script location and shared library (colors, logging, validation) -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# shellcheck source=../common/wallarm-lib.sh -source "$SCRIPT_DIR/../common/wallarm-lib.sh" - -set -euo pipefail -trap early_error_handler ERR - -# ============================================================================== -# CHECK FOR SUDO / ROOT PRIVILEGES -# ============================================================================== -if [ "$EUID" -ne 0 ]; then - echo -e "${RED}${BOLD}ERROR:${NC} This script must be run with sudo or as root." - echo -e "${YELLOW}Please run: sudo $0${NC}" - exit 1 -fi - -# ============================================================================== -# CONFIGURATION -# ============================================================================== -CONFIG_GLOB="/etc/nginx/conf.d/wallarm-*.conf" -CONFIG_FILE="" -INSTANCE_NAME="" - -# ============================================================================== -# FUNCTIONS -# ============================================================================== - -# Find the Wallarm NGINX config file(s) -find_wallarm_config() { - local configs=() - while IFS= read -r file; do - configs+=("$file") - done < <(ls $CONFIG_GLOB 2>/dev/null) - - if [ ${#configs[@]} -eq 0 ]; then - echo -e "${RED}No Wallarm NGINX configuration found ($CONFIG_GLOB).${NC}" - echo -e "${YELLOW}Has the native deployment been run? Check /etc/nginx/conf.d/wallarm-*.conf${NC}" - exit 1 - elif [ ${#configs[@]} -eq 1 ]; then - CONFIG_FILE="${configs[0]}" - INSTANCE_NAME=$(basename "$CONFIG_FILE" | sed 's/^wallarm-//; s/\.conf$//') - echo -e "${GREEN}Found Wallarm config: $CONFIG_FILE${NC}" - else - echo -e "${YELLOW}Multiple Wallarm NGINX configs found:${NC}" - for i in "${!configs[@]}"; do - echo "$((i+1)). ${configs[$i]}" - done - read -r -p "Select config number: " choice - if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le ${#configs[@]} ]; then - CONFIG_FILE="${configs[$((choice-1))]}" - INSTANCE_NAME=$(basename "$CONFIG_FILE" | sed 's/^wallarm-//; s/\.conf$//') - else - echo -e "${RED}Invalid selection.${NC}" - exit 1 - fi - fi -} - -# Parse current configuration to get existing values -parse_current_config() { - local config_file="$1" - current_mode=$(grep -oP 'wallarm_mode\s+\K\S+' "$config_file" | head -1) - current_proxies=$(grep -oP 'set_real_ip_from\s+\K\S+' "$config_file") -} - -# Update configuration -update_config() { - local config_file="$1" - local backup_file="$config_file.backup.$(date +%Y%m%d_%H%M%S)" - - echo -e "${YELLOW}Backing up current config to $backup_file${NC}" - cp "$config_file" "$backup_file" - - echo -e "\n${CYAN}${BOLD}Current set_real_ip_from entries:${NC}" - if [ -n "$current_proxies" ]; then - while read -r proxy; do - echo " $proxy" - done <<< "$current_proxies" - else - echo " (none)" - fi - - echo -e "\n${YELLOW}Do you want to change the trusted proxy IPs/CIDRs? (y/N)${NC}" - read -r change_proxy - new_proxies=() - if [[ "$change_proxy" =~ ^[Yy]$ ]]; then - echo -e "${YELLOW}Enter new trusted proxy IPs/CIDRs (space-separated, or empty to remove all):${NC}" - read -r new_proxies_input - if [[ -n "$new_proxies_input" ]]; then - IFS=' ' read -ra proxy_array <<< "$new_proxies_input" - for proxy in "${proxy_array[@]}"; do - proxy=$(echo "$proxy" | xargs) - if validate_ip_or_cidr "$proxy"; then - new_proxies+=("$proxy") - else - echo -e "${RED}Invalid format: $proxy. Skipping.${NC}" - fi - done - fi - else - # Keep existing - while read -r proxy; do - new_proxies+=("$proxy") - done <<< "$current_proxies" - fi - - echo -e "\n${CYAN}${BOLD}Current wallarm_mode:${NC} ${current_mode:-not set}" - echo -e "${YELLOW}Do you want to change the wallarm_mode? (y/N)${NC}" - read -r change_mode - if [[ "$change_mode" =~ ^[Yy]$ ]]; then - echo -e "${YELLOW}Select new mode:${NC}" - echo "1. monitoring" - echo "2. block" - read -r mode_choice - case "$mode_choice" in - 1) new_mode="monitoring" ;; - 2) new_mode="block" ;; - *) echo -e "${RED}Invalid choice, keeping current mode.${NC}"; new_mode="$current_mode" ;; - esac - else - new_mode="$current_mode" - fi - - # Rebuild the config file - temp_config=$(mktemp) - - in_server_block=false - while IFS= read -r line; do - if [[ "$line" =~ ^[[:space:]]*server[[:space:]]*{ ]]; then - in_server_block=true - fi - - if $in_server_block; then - if [[ "$line" =~ ^[[:space:]]*set_real_ip_from[[:space:]]+ ]]; then - continue - fi - if [[ "$line" =~ ^[[:space:]]*wallarm_mode[[:space:]]+ ]]; then - continue - fi - if [[ "$line" =~ ^[[:space:]]*real_ip_header[[:space:]]+ ]]; then - continue - fi - if [[ "$line" =~ ^[[:space:]]*real_ip_recursive[[:space:]]+ ]]; then - continue - fi - fi - - echo "$line" >> "$temp_config" - - if $in_server_block && [[ "$line" =~ ^[[:space:]]*}$ ]]; then - in_server_block=false - if [ ${#new_proxies[@]} -gt 0 ]; then - for proxy in "${new_proxies[@]}"; do - echo " set_real_ip_from $proxy;" >> "$temp_config" - done - echo " real_ip_header X-Real-IP;" >> "$temp_config" - echo " real_ip_recursive on;" >> "$temp_config" - fi - if [ -n "$new_mode" ]; then - echo " wallarm_mode $new_mode;" >> "$temp_config" - fi - fi - done < "$config_file" - - mv "$temp_config" "$config_file" - chmod 644 "$config_file" - - echo -e "${GREEN}Configuration updated.${NC}" -} - -reload_nginx() { - echo -e "${YELLOW}Testing NGINX configuration...${NC}" - if ! sudo nginx -t; then - echo -e "${RED}NGINX configuration test failed. Restoring backup...${NC}" - cp "$CONFIG_FILE.backup."*. "$CONFIG_FILE" 2>/dev/null || true - exit 1 - fi - - echo -e "${YELLOW}Reloading NGINX to apply changes...${NC}" - sudo systemctl reload nginx 2>/dev/null || sudo nginx -s reload 2>/dev/null || { - sudo systemctl restart nginx 2>/dev/null || { - echo -e "${RED}Could not reload NGINX. Please do it manually: sudo systemctl reload nginx${NC}" - exit 1 - } - } - echo -e "${GREEN}NGINX reloaded.${NC}" -} - -main() { - echo -e "${BLUE}${BOLD}" - echo "╔══════════════════════════════════════════════════════════════╗" - echo "║ WALLARM RECONFIGURATION SCRIPT (Native) - V1.0 ║" - echo "║ Modify NGINX config (trusted proxies / mode) ║" - echo "╚══════════════════════════════════════════════════════════════╝${NC}" - - find_wallarm_config - - parse_current_config "$CONFIG_FILE" - update_config "$CONFIG_FILE" - - echo -e "${YELLOW}Do you want to reload NGINX now? (Y/n)${NC}" - read -r reload_choice - if [[ ! "$reload_choice" =~ ^[Nn]$ ]]; then - reload_nginx - else - echo -e "${YELLOW}Changes will take effect after NGINX reload.${NC}" - echo -e "You can reload later with: sudo systemctl reload nginx" - fi - - echo -e "\n${GREEN}${BOLD}Reconfiguration completed.${NC}" -} - -main "$@" diff --git a/native/wallarm-ct-uninstall.sh b/native/wallarm-ct-uninstall.sh deleted file mode 100755 index c20b85e..0000000 --- a/native/wallarm-ct-uninstall.sh +++ /dev/null @@ -1,299 +0,0 @@ -#!/bin/bash -# ============================================================================== -# WALLARM UNINSTALL SCRIPT - V1.0 (Native deployment) -# ============================================================================== -# Purpose: Safely remove a native (no-Docker) Wallarm filtering node -# Features: -# - Interactive confirmation with safety checks -# - Removes Wallarm NGINX configuration (with backup) -# - Restores disabled default NGINX sites -# - Uninstalls Wallarm packages and repository definitions -# - Removes /opt/wallarm node data -# - Preserves user data and logs (with option to remove) -# - DAU-friendly warnings and confirmations -# ============================================================================== - -# Script location and shared library (colors, logging, validation) -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# shellcheck source=../common/wallarm-lib.sh -source "$SCRIPT_DIR/../common/wallarm-lib.sh" - -# Strict error handling -set -euo pipefail -trap early_error_handler ERR - -# ============================================================================== -# CONFIGURATION -# ============================================================================== -CONFIG_GLOB="/etc/nginx/conf.d/wallarm-*.conf" -DEFAULT_BACKUP_GLOB="/etc/nginx/sites-enabled/*.bak" -WALLARM_NODE_DIR="/opt/wallarm" - -# ============================================================================== -# FUNCTIONS -# ============================================================================== - -# Ask for confirmation -confirm() { - local prompt="$1" - local default="${2:-n}" - local options="[y/N]" - - if [ "$default" = "y" ]; then - options="[Y/n]" - fi - - echo -e -n "${YELLOW}${prompt} ${options}${NC} " - read -r response - - case "$response" in - [yY][eE][sS]|[yY]) return 0 ;; - [nN][oO]|[nN]) return 1 ;; - "") - if [ "$default" = "y" ]; then - return 0 - else - return 1 - fi - ;; - *) return 1 ;; - esac -} - -# Detect the package manager in use -detect_package_manager() { - if command -v apt-get >/dev/null 2>&1; then - echo "apt" - elif command -v yum >/dev/null 2>&1; then - echo "yum" - elif command -v dnf >/dev/null 2>&1; then - echo "dnf" - elif command -v apk >/dev/null 2>&1; then - echo "apk" - else - echo "unknown" - fi -} - -# Remove Wallarm NGINX configuration files -remove_nginx_configs() { - log_message "INFO" "Looking for Wallarm NGINX configurations..." - - local configs=() - while IFS= read -r file; do - configs+=("$file") - done < <(ls $CONFIG_GLOB 2>/dev/null) - - if [ ${#configs[@]} -eq 0 ]; then - log_message "INFO" "No Wallarm NGINX configurations found" - return - fi - - log_message "INFO" "Found ${#configs[@]} Wallarm NGINX configuration(s)" - for file in "${configs[@]}"; do - if confirm "Remove $file? (backup created)" "y"; then - cp "$file" "$file.uninstall-$(date +%Y%m%d_%H%M%S).bak" - rm -f "$file" - log_message "SUCCESS" "Removed $file (backup created)" - else - log_message "INFO" "Skipping $file" - fi - done -} - -# Restore any default NGINX sites we disabled during deployment -restore_default_sites() { - log_message "INFO" "Looking for disabled default NGINX sites..." - - local restored=0 - while IFS= read -r backup; do - if [ -f "$backup" ]; then - local target="${backup%.bak}" - log_message "INFO" "Restoring $target from $backup" - if confirm "Restore $target?" "y"; then - cp "$backup" "$target" - rm -f "$backup" - restored=$((restored + 1)) - fi - fi - done < <(ls $DEFAULT_BACKUP_GLOB 2>/dev/null) - - if [ "$restored" -gt 0 ]; then - log_message "SUCCESS" "Restored $restored default site(s)" - else - log_message "INFO" "No disabled default sites found" - fi -} - -# Reload NGINX to drop the removed configurations -reload_nginx() { - log_message "INFO" "Testing and reloading NGINX..." - - if sudo nginx -t 2>/dev/null; then - sudo systemctl reload nginx 2>/dev/null || sudo nginx -s reload 2>/dev/null || true - log_message "SUCCESS" "NGINX reloaded" - else - log_message "WARNING" "NGINX configuration test failed - reload skipped" - echo -e "${YELLOW}Run 'sudo nginx -t' manually to diagnose the issue.${NC}" - fi -} - -# Uninstall Wallarm packages via the system package manager -remove_wallarm_packages() { - local pkg_manager - pkg_manager=$(detect_package_manager) - - log_message "INFO" "Detected package manager: $pkg_manager" - - if ! confirm "Uninstall Wallarm packages? (wallarm-node, wallarm modules)" "y"; then - log_message "INFO" "Skipping Wallarm package removal" - return - fi - - case "$pkg_manager" in - "apt") - log_message "INFO" "Removing Wallarm packages (apt)..." - sudo apt-get purge -y "wallarm-node" "wallarm-node-nginx" "nginx-module-wallarm*" 2>/dev/null || true - sudo apt-get autoremove -y 2>/dev/null || true - ;; - "yum") - log_message "INFO" "Removing Wallarm packages (yum)..." - sudo yum remove -y "wallarm-node" "nginx-module-wallarm*" 2>/dev/null || true - ;; - "dnf") - log_message "INFO" "Removing Wallarm packages (dnf)..." - sudo dnf remove -y "wallarm-node" "nginx-module-wallarm*" 2>/dev/null || true - ;; - "apk") - log_message "INFO" "Removing Wallarm packages (apk)..." - sudo apk del "wallarm-node" "nginx-module-wallarm" 2>/dev/null || true - ;; - *) - log_message "WARNING" "Unknown package manager. Please remove Wallarm packages manually." - echo -e "${YELLOW}Relevant packages usually include: wallarm-node, nginx-module-wallarm${NC}" - return - ;; - esac - - log_message "SUCCESS" "Wallarm packages removed" -} - -# Remove Wallarm repository definitions added by the installer -remove_wallarm_repos() { - log_message "INFO" "Removing Wallarm repository definitions..." - - local removed=0 - while IFS= read -r file; do - if [ -f "$file" ]; then - sudo rm -f "$file" - log_message "SUCCESS" "Removed repo file: $file" - removed=$((removed + 1)) - fi - done < <(ls /etc/apt/sources.list.d/*wallarm* /etc/yum.repos.d/*wallarm* 2>/dev/null) - - if [ "$removed" -eq 0 ]; then - log_message "INFO" "No Wallarm repository files found" - fi -} - -# Remove Wallarm node data directory -remove_wallarm_data() { - if [ -d "$WALLARM_NODE_DIR" ]; then - log_message "WARNING" "Found Wallarm data directory: $WALLARM_NODE_DIR" - log_message "WARNING" "This contains node registration and local data." - if confirm "Remove $WALLARM_NODE_DIR? (node will need re-registration)" "n"; then - sudo rm -rf "$WALLARM_NODE_DIR" - log_message "SUCCESS" "Removed $WALLARM_NODE_DIR" - else - log_message "INFO" "Skipping removal of $WALLARM_NODE_DIR" - fi - else - log_message "INFO" "No Wallarm data directory found" - fi -} - -# Remove Wallarm log files (optional) -remove_wallarm_logs() { - local log_dir="$HOME/logs" - if [ -d "$log_dir" ]; then - log_message "INFO" "Found log directory: $log_dir" - if [ -z "$(ls -A "$log_dir" 2>/dev/null)" ]; then - log_message "INFO" "Log directory is empty, removing..." - sudo rmdir "$log_dir" 2>/dev/null || true - else - log_message "INFO" "Log directory contains files, preserving..." - fi - fi - - if [ -f ".env" ]; then - if confirm "Remove .env preflight file?" "n"; then - rm -f ".env" - log_message "SUCCESS" "Removed .env file" - fi - fi -} - -# ============================================================================== -# MAIN -# ============================================================================== - -main() { - echo -e "${CYAN}${BOLD}" - echo "╔══════════════════════════════════════════════════════════════╗" - echo "║ WALLARM UNINSTALLATION (Native) ║" - echo "╚══════════════════════════════════════════════════════════════╝" - echo -e "${NC}" - - echo -e "${YELLOW}This script will remove the native Wallarm filtering node.${NC}" - echo -e "${YELLOW}You will be asked for confirmation before each destructive operation.${NC}" - echo "" - - if ! confirm "Do you want to continue with the uninstallation?" "n"; then - log_message "INFO" "Uninstallation cancelled by user" - exit 0 - fi - - # Step 1: Remove Wallarm NGINX configurations - echo "" - echo -e "${CYAN}${BOLD}Step 1: Remove Wallarm NGINX configurations${NC}" - remove_nginx_configs - restore_default_sites - reload_nginx - - # Step 2: Uninstall Wallarm packages - echo "" - echo -e "${CYAN}${BOLD}Step 2: Uninstall Wallarm packages${NC}" - remove_wallarm_packages - remove_wallarm_repos - - # Step 3: Remove Wallarm data - echo "" - echo -e "${CYAN}${BOLD}Step 3: Remove Wallarm data${NC}" - remove_wallarm_data - - # Step 4: Cleanup - echo "" - echo -e "${CYAN}${BOLD}Step 4: Logs and files cleanup${NC}" - if confirm "Remove Wallarm log files and .env?" "n"; then - remove_wallarm_logs - else - log_message "INFO" "Skipping log/file cleanup" - fi - - # Final message - echo "" - echo -e "${GREEN}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}" - echo -e "${GREEN}${BOLD}║ UNINSTALLATION COMPLETE ║${NC}" - echo -e "${GREEN}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}" - echo "" - echo -e "${GREEN}The native Wallarm filtering node has been removed.${NC}" - echo "" - echo -e "${YELLOW}Note:${NC}" - echo -e " • NGINX itself was kept installed (may be used by other applications)" - echo -e " • The Wallarm module may remain in NGINX's modules directory" - echo -e " • Wallarm repositories were removed from your package sources" - echo "" -} - -# Run main function -main "$@" diff --git a/setup.sh b/setup.sh index 0e0e0c2..1990ede 100755 --- a/setup.sh +++ b/setup.sh @@ -41,10 +41,6 @@ DOCKER_SCRIPTS=( ) NATIVE_SCRIPTS=( - "wallarm-ct-check.sh" - "wallarm-ct-deploy.sh" - "wallarm-ct-reconfigure.sh" - "wallarm-ct-uninstall.sh" "wallarm-native.sh" ) @@ -139,11 +135,11 @@ echo -e " 3. Reconfigure existing node: ${YELLOW}./docker/wallarm-ct-reconfig echo -e " 4. Uninstall a node: ${YELLOW}./docker/wallarm-ct-uninstall.sh${NC}" echo echo -e " Native deployment (no Docker):" -echo -e " 1. Run the preflight check: ${YELLOW}./native/wallarm-ct-check.sh${NC}" -echo -e " 2. Deploy a Wallarm node: ${YELLOW}./native/wallarm-ct-deploy.sh${NC}" -echo -e " 3. Unified node manager: ${YELLOW}./native/wallarm-native.sh --preflight${NC} (then --install)" -echo -e " 4. Reconfigure existing node: ${YELLOW}./native/wallarm-ct-reconfigure.sh${NC}" -echo -e " 5. Uninstall a node: ${YELLOW}./native/wallarm-ct-uninstall.sh${NC}" +echo -e " 1. Run the preflight check: ${YELLOW}sudo ./native/wallarm-native.sh --preflight${NC}" +echo -e " 2. Deploy Wallarm nodes: ${YELLOW}sudo ./native/wallarm-native.sh --install${NC}" +echo -e " 3. Update a node's config: ${YELLOW}sudo ./native/wallarm-native.sh --config --node NAME --address IP:PORT${NC}" +echo -e " 4. Remove a node: ${YELLOW}sudo ./native/wallarm-native.sh --remove --node NAME${NC}" +echo -e " 5. Show node status: ${YELLOW}./native/wallarm-native.sh --status${NC}" echo echo -e "${YELLOW}Note: Some scripts require sudo. Run them with: sudo ./